<?php

namespace app\mp\admin;

use app\common\service\GeneralMaterial as GeneralMaterialService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\Stock as StockService;
use app\common\service\StockLog as StockLogService;
use app\common\service\StockUse as StockUseService;
use app\system\admin\Admin;
use think\Db;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;

/**
 * 裁床/车间/尾部工价管理与核算
 * @author sparkguo
 */
class ProcessPriceOrder extends Admin
{

    public function initialize(){
        parent::initialize();
    }

    //裁床工价审核
    public function cutStatements(){
        $status = $this->request->param('status/d', 1);
        $factoryKV = getFactoryKV(false);
        $systemUserKV = getSystemUserKV(null);
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $where[] = [
                ['caichuang_over_time', '>', 1646064000],
                ['stock_type','not in','10,11']
            ];
            $factoryId   = $this->request->param('factory_id/s', '');
            $client_ordernum   = $this->request->param('client_ordernum', '');
            $sku = $this->request->param('sku', '');
            $overDateRange=$this->request->param('create_date_range');
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $factoryIdarr=array_keys($factoryKV);
            if ($factoryId) {
                $where[] = ['o.factory_id', '=', $factoryId];
            }else{
                $where[] = ['o.factory_id', 'in', $factoryIdarr];
            }
            list($startTime, $endTime) = $overDateRange != '' ? array_map('strtotime', explode('~', $overDateRange)) : [strtotime(date("Y-m-01 00:00:00",strtotime("-6 month"))),time()];
            if($sku) $where[] = ['o.sku', '=', $sku];
            if($client_ordernum) $where[] = ['o.client_ordernum', '=', $client_ordernum];
            if($overDateRange) $where[] = ['o.caichuang_over_time', 'between', [$startTime, $endTime+86399]];
            $checksCountWhere=$where;
            if($status==1){
                $where[] = ["o.id", 'not in', db('order_progress_price')->column('order_id')];
            }else{
                $where[] = ["o.id", 'in', db('order_progress_price')->column('order_id')];
            }

            $order = 'id desc';
            $field1='o.id,caichuang_over_time,o.client_ordernum,o.sku,quantity,caichuang_chuanghao,o.caichuang_user_id,caichuang_type,o.caichuang_position,o.`factory_id`
        ,sum(osize.shicai_count) sum_shicai_count,o.caichuang_user_id
        ,sp.process_price,sp.process_name
        ,s.pic,s.ori_pic';
            $list =db('order o')->where($where)->field($field1)
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('sku_process_price sp', 'sp.sku=o.sku and sp.process_stage=1', 'left')
                ->group('o.id')
                ->page($page)->limit($limit)->order($order)->select();
            $count =db('order o')->where($where)->count('id');
            foreach ($list as $k => &$v) {
                $orderProcessChangePrice= db("order_progress_price_change")->where([
                    ['process_keywords', '=', 'caijian'],
                    ['order_id', '=',$v['id']],
                ])->value('process_price');
                $v['process_price']=!empty($orderProcessChangePrice)? $orderProcessChangePrice : $v['process_price'] ; //优先取自定义修改的单价
                $v['process_price']=!empty($v['process_price']) ? $v['process_price'] : 0.3; //优先取款式工价表单价
                $list[$k]['ft_name']=$factoryKV[$v['factory_id']];
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                @$list[$k]['caichuang_user_name'] =$systemUserKV[$v['caichuang_user_id']];
                $list[$k]['caichuang_over_time'] = intval($list[$k]['caichuang_over_time']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['caichuang_over_time']);//出货时间
                $list[$k]['caichuang_position_txt'] = arrayGet(config('mimo.caichuang_position'), $v['caichuang_position'], '');
            }
            $needcheckCount=db('order o')->where($checksCountWhere)->where([["o.id", 'not in', db('order_progress_price')->column('order_id')]])->count('id');
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'needcheckCount'=>$needcheckCount,
                'checkedCount'=>db('order o')->where($checksCountWhere)->where([["o.id", 'in', db('order_progress_price')->column('order_id')]])->count(),
                'count' => $count,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status' => $status,

            ];
            return json($result);
        }
        $statData =[1=>0,2=>0];
        $assign = [
            'status' => 1,
            'statData' => $statData,
            'factoryKV' => [0 => '请选择'] + getFactoryKV(false),
            'caichuang_position' => [-1 => '请选择'] + config('mimo.caichuang_position'),
        ];
        return $this->assign($assign)->fetch();
    }

    public function cutStatementsCheck(){
        //1,参数处理
        $status = $this->request->param('status/d', 0);
        $process_stage = $this->request->param('process_stage/d', 0);
        $ids = $this->request->param('id', []);
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }

        $action=$this->request->param('action','');

        $where[] = [
            ['o.id', 'in', $ids],
        ];
        $field1='o.id,caichuang_over_time,o.client_ordernum,o.sku,quantity,caichuang_chuanghao,caichuang_user_id,caichuang_type,o.caichuang_position,o.`factory_id`
            ,sum(osize.shicai_count) sum_shicai_count,sp.process_price';
        $list =db('order o')->where($where)->field($field1)
            ->join('order_size osize ', 'osize.order_id=o.id', 'left')
            ->join('sku_process_price sp ', 'sp.sku=o.sku and sp.process_stage=1', 'left')
            ->group('o.id')->select();

        foreach ($list as $key=>$v){
            $cut_statement=[];
            $orderProcessChangePrice= db("order_progress_price_change")->where([
                ['process_keywords', '=', 'caijian'],
                ['order_id', '=',$v['id']],
            ])->value('process_price');
            $v['process_price']=!empty($orderProcessChangePrice)? $orderProcessChangePrice : $v['process_price'] ; //优先取自定义修改的单价
            $v['process_price']=!empty($v['process_price']) ? $v['process_price'] : 0.3; //优先取款式工价表单价
            $temp = db('order_progress_price')->insert([
                'order_id' => $v['id'],
                'client_ordernum' => $v['client_ordernum'],
                'sku' => $v['sku'],
                'process_stage' => 1,
                'process_name' => '裁床',
                'pay_count'=>$v['sum_shicai_count'],
                'process_price' =>$v['process_price'],
                'status' => 1120,
                'action_str' => serialize([
                    [ADMIN_ID, time(), '初审完成'],
                ]),
                'create_time' => time(),
                'update_time' => time(),
            ]);
        }
        return $this->Json(1, '审核成功', $temp);
    }

    //车间对帐单审核
    public function sewStatements(){
        $action=$this->request->param('action', '');
        $status = $this->request->param('status/d', 1);
        $process_stage=$this->request->param('process_stage/d', 2); //2车间与尾部对账区别参数,3尾部
        $user_name=$this->request->param('user_name', '');
        $group_name=$this->request->param('group_name', '');
        $user_number=$this->request->param('user_number', '');
        $process_name=$this->request->param('process_name', '');
        $factoryKV = getFactoryKV(false);
        if($action=='getbilldetails'){  //帐单明细 可编辑
            return $this->_getbilldetails();
        }
        if($action=='salaryDetailList'){ //复合对账 账单明细
            return $this->salaryDetailList();
        }
        if($action=='addProcessCount'){  //增减结算数 及 批量备注功能
            return $this->addPorcess();
        }
        if($action=='importCostBroke'){  //导入成本报损数
            return $this->importCostBroke();
        }
        $overDateRange=$this->request->param('create_date_range','');
        $instock_date_range=$this->request->param('instock_date_range',date("Y-m-01 00:00:00",strtotime("-1 month"))."~".date("Y-m-04 23:58:59"));
        list($startTime1, $endTime1) = $instock_date_range != '' ? array_map('strtotime', explode('~', $instock_date_range)) : [0,0];
        list($startTime, $endTime) = $overDateRange != '' ? array_map('strtotime', explode('~', $overDateRange)) : [0,0];
        if ($this->request->isAjax()|| $this->request->param('export')) {
            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $export     = $this->request->param('export/d', 0);
            $factoryId   = $this->request->param('factory_id/s', '');
            $client_ordernum   = $this->request->param('client_ordernum', '');
            $diff_count=$this->request->param("diff_count");
            $process_price=$this->request->param("process_price",'');
            $diff_count_logic=$this->request->param("diff_count_logic");
            $sku = $this->request->param('sku', '');
            $factoryIdarr=array_keys($factoryKV);
            $where[]=['process_stage', 'eq', $process_stage];
            $where[]=['up.is_disabled','eq',0];
            $where[]=['up.order_id','gt',0];
            if($client_ordernum=='') $where[]=['o.store_count','gt',0]; //无入仓数的不出现
            if($process_price!==''){
                $where[]=['process_price','eq',$process_price];
            }
            if(!empty($user_number)) $where[]=['user_number','like',"%".$user_number."%"];
            if(!empty($group_name)){
                $where[]=['group_name','like',"%".$group_name."%"];
            }
            if(!empty($process_name)){
                $where[]=['up.process_name','like',"%".$process_name."%"];
            }

            if(!empty($instock_date_range)){
                $where[] = ['o.store_time', 'between', [$startTime1, $endTime1+86399]];
            }
            /*if($status==1){ //待审
                $where[]=['check_state', 'eq', 0];
            }else{
                $where[]=['check_state', 'gt', 0];
            }*/
            if ($export) {
                set_time_limit(0);
                $page = 1;$limit = 99999;
            }
            if($sku) $where[] = ['o.sku', '=', $sku];
            if($client_ordernum) $where[] = ['o.client_ordernum', '=', $client_ordernum];
            if($overDateRange) $where[] = ['up.work_time', 'between', [$startTime, $endTime+86399]];
            if($factoryId) $where[] = ['up.factory_name', '=', $factoryId];
            if(in_array($status,[1,2])){ //等待对帐/对帐中
                $retOrderids=db('user_process up')->where($where)
                    ->join('order o', 'up.order_id = o.id','left')->group("order_id")->column('order_id','o.client_ordernum');
                $retOrderids=empty($retOrderids) ? ['ordernum_none'=>'orderid_none'] : $retOrderids ;
                //入库数
                $instockRet=db("sku_stock_log log")
                    ->field("sum(available_count) as available_count,log.factory_id,log.client_ordernum")
                    ->where("log.client_ordernum","in",array_keys($retOrderids))
                    ->where('action_type','eq',1)->group("log.client_ordernum")->buildSql();//+defective_count 入库数不含次品
                //出库其它单库存数统计
                $checkOutStockRet=db("sku_stock_log log")
                    ->field("sum(available_count) as available_checkout_count,log.out_ordernum,log.client_ordernum")
                    //->where("log.client_ordernum","in",array_keys($retOrderids))
                    ->where('action_type','eq',2)->group("log.out_ordernum")->buildSql();

                $processCountRet=db('user_process up')->field("store_count as store_count2,up.order_id,process_name,sum(up.quintity) as tot_quintity2,up.id as id,sum(process_quintity) as process_quintity2,up23.available_count,
                outstock.available_checkout_count,upexp.broke_make_count,upexp.broke_cost_count")
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join('user_process_ext upexp', 'up.order_id = upexp.order_id','left')
                    ->join([$instockRet=> 'up23'], 'o.client_ordernum = up23.client_ordernum','left')
                    ->join([$checkOutStockRet=> 'outstock'], 'o.client_ordernum = outstock.out_ordernum','left')
                    ->where("up.order_id","in",$retOrderids)
                    ->group('up.order_id,process_name')->buildSql();

                //搜索差异件数时的语句
                $processCountRet2=db('user_process up')->field("store_count as store_count2,up.order_id,process_name,sum(up.quintity) as tot_quintity2,up.id as id,sum(process_quintity) as process_quintity2,upexp.broke_cost_count,
                (CASE  WHEN up23.available_count IS NULL THEN 0 ELSE up23.available_count END) as available_count,
                (CASE  WHEN upexp.broke_make_count IS NULL THEN 0 ELSE upexp.broke_make_count END) as broke_make_count,
                (CASE  WHEN outstock.available_checkout_count IS NULL THEN 0 ELSE outstock.available_checkout_count END) as available_checkout_count")
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join('user_process_ext upexp', 'up.order_id = upexp.order_id','left')
                    ->join([$instockRet=> 'up23'], 'o.client_ordernum = up23.client_ordernum','left')
                    ->join([$checkOutStockRet=> 'outstock'], 'o.client_ordernum = outstock.out_ordernum','left')
                    ->where("up.order_id","in",$retOrderids)
                    ->group('order_id,process_name')->buildSql();

                $sqlwhere='';$joinType='left';
                if($diff_count!=''){
                    $logic_arr=['gt'=>'>','lt'=>"<",'eq'=>'='];
                    if(!isset($logic_arr[$diff_count_logic])) $this->error('件数差异条件异常');
                    $processCountRet=$processCountRet2;
                    $diff_count_logic= $logic_arr[$diff_count_logic];
                    $sqlwhere .=" and (up2.available_count+up2.store_count2+broke_make_count-available_checkout_count) - tot_quintity2 $diff_count_logic".$diff_count."";
                    $joinType='inner';
                }
                $total = db('user_process up')
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join([$processCountRet=> 'up2'], 'up.order_id = up2.order_id and up.process_name=up2.process_name'.$sqlwhere,$joinType)
                    ->where($where)->where(['check_state' =>$status-1])
                    ->group('up.order_id,up.process_name,up.user_number')->count("up.id");
                if($limit>20 && $total>20000){
                    $this->error('导出数据过大已超过20000条，请筛选后再做导出');
                }
                $list = db('user_process up')
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join([$processCountRet=> 'up2'], 'up.order_id = up2.order_id and up.process_name=up2.process_name'.$sqlwhere,$joinType)
                    //->join('sku sk', 'o.sku = sk.sku','left')
                    ->where($where)->where(['check_state' =>$status-1])->page($page)->field("*,up.order_id as order_id,up.process_name as process_name,FROM_UNIXTIME(work_time,'%Y-%m') as month,scan_date,
                    sum(up.quintity) as tot_quintity,group_concat(up.check_remark SEPARATOR ' ') as check_remark,o.store_time,
                    sum(up.process_quintity) as process_quintity,sum(up.old_quintity) as old_quintity,up.id as id")
                    ->group('up.order_id,up.process_name,up.user_number')->limit($limit)->select();//->order('up.order_id asc,process_name desc')

                //总计数据  加工数量  结算单价 结算数量 累计结算 MES入仓 米莫入库  结算金额
                $countdata=db('user_process up')
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join([$processCountRet=> 'up2'], 'up.order_id = up2.order_id and up.process_name=up2.process_name'.$sqlwhere,$joinType)->where($where)
                    ->field("sum(up.quintity) as tot_quintity,sum(process_quintity) as process_quintity,sum(quintity * process_price ) as money_total,'' as process_price,'-1' as order_id,
                    '总计'as work_time,'' as user_name,'' as user_number,'' as bar_num,'' as shicai_count,'' as flag_only")
                    ->find();
                $countdata['client_ordernum']=$countdata['sku']=$countdata['jiaohuo_count']=$countdata['count_diff']=$countdata['tot_process_quintity']='';
                $countdata['creater_name']=$countdata['check_user']='';
                $countdata['process_count']='';
                $countdata['money_total']=sprintf('%.2f',$countdata['money_total']);
                //$list[]=$countdata;

                $needcheckCount=db('user_process up')
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join([$processCountRet=> 'up2'], 'up.order_id = up2.order_id and up.process_name=up2.process_name'.$sqlwhere,$joinType)
                    ->where($where)->where(['check_state' =>0])
                    ->group('up.order_id,up.process_name,up.user_number')->count("up.id");
                $checkedCount=db('user_process up')
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join([$processCountRet=> 'up2'], 'up.order_id = up2.order_id and up.process_name=up2.process_name'.$sqlwhere,$joinType)
                    ->where($where)->where(['check_state' =>1])
                    ->group('up.order_id,up.process_name,up.user_number')->count("up.id");

            }elseif($status==3){ //复合对帐
                $total = db('user_process up')->where($where)->where(['check_state' =>2])->join('order o', 'up.order_id = o.id','left')
                    ->group("user_number,FROM_UNIXTIME(work_time,'%Y-%m')")->count();
                $list = db('user_process up')
                    ->join('order o', 'up.order_id = o.id','left')
                    //->join('sku sk', 'o.sku = sk.sku','left')
                    ->where($where)->where(['check_state' =>2])->page($page)
                    ->field("*,sum(up.quintity) as tot_quintity,sum(up.process_quintity) as process_quintity,sum(up.old_quintity) as old_quintity,scan_date,0 as broke_make_count,0 as broke_cost_count,
                    sum(up.quintity*up.process_price) process_total_money,up.id as id,FROM_UNIXTIME(work_time,'%Y-%m') as month")
                    ->group("user_number,pay_state,pay_code,FROM_UNIXTIME(work_time,'%Y-%m')")->limit($limit)->order('up.order_id asc,process_name desc')->select();
                $needcheckCount=$checkedCount='---';
            }elseif($status==4){ //对帐明细
                //入库数
                $instockRet=db("sku_stock_log log")
                    ->field("sum(available_count) as available_count,log.factory_id,log.client_ordernum")
                    ->where('action_type','eq',1)->group("log.client_ordernum")->buildSql();//+defective_count 入库数不含次品
                //出库其它单库存数统计
                $checkOutStockRet=db("sku_stock_log log")
                    ->field("sum(available_count) as available_checkout_count,log.out_ordernum,log.client_ordernum")
                    ->where('action_type','eq',2)->group("log.out_ordernum")->buildSql();

                $processCountRet=db('user_process up')->field("store_count as store_count2,up.order_id,process_name,sum(up.quintity) as tot_quintity2,up.id as id,sum(process_quintity) as process_quintity2,up23.available_count,
                outstock.available_checkout_count,upexp.broke_make_count,upexp.broke_cost_count")
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join('user_process_ext upexp', 'up.order_id = upexp.order_id','left')
                    ->join([$instockRet=> 'up23'], 'o.client_ordernum = up23.client_ordernum','left')
                    ->join([$checkOutStockRet=> 'outstock'], 'o.client_ordernum = outstock.out_ordernum','left')
                    ->group('up.order_id,process_name')->buildSql();

                $total = db('user_process up')->where($where)->where(['check_state' =>2])->group('order_id,process_name,user_number')
                    ->join('order o', 'up.order_id = o.id','left')->count();
                $sqlwhere='';$joinType='left';
                $list = db('user_process up')
                    ->join('order o', 'up.order_id = o.id','left')
                    ->join([$processCountRet=> 'up2'], 'up.order_id = up2.order_id and up.process_name=up2.process_name'.$sqlwhere,$joinType)
                    ->join('user_process_ext upexp', 'up.order_id = upexp.order_id','left')
                    ->join('sku sk', 'o.sku = sk.sku','left')
                    ->where($where)->where(['check_state' =>2])->page($page)->field("*,up.id as id,sum(up.quintity) as tot_quintity,sum(up.process_quintity) as process_quintity,up.order_id as order_id,
                    FROM_UNIXTIME(work_time,'%Y-%m') as month,o.store_time")
                    ->group('up.order_id,up.process_name,user_number')
                    ->limit($limit)->order('up.order_id asc,up.process_name desc')->select();
                $needcheckCount=$checkedCount='---';
            }
            $systemUserKV = getSystemUserKV(null);
            if($total>0){
                //实裁数 车间交货数
                $finishCountList =db('order_size osize')->where([ ['order_id', 'in', array_column($list,'order_id')]])
                    ->field("order_id,sum(osize.shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(sew_cut_count) as sew_cut_count,sum(delivery_count) as delivery_count")
                    ->group('order_id')->select();
                //累计加工数
                $processCountRet=db('user_process up')->where([['order_id', 'in', array_column($list,'order_id')]])
                    ->field("*,sum(up.quintity) as tot_quintity,up.id as id,sum(process_quintity) as process_quintity")
                    ->group('order_id,process_name')->select();
                //米莫入库数统计[['client_ordernum','eq', $item['client_ordernum']]

                $processCountList=[]; //各订单工序 累计加工数数组
                foreach ($processCountRet as $key => $item) {
                    $processCountList[$item['order_id'].$item['process_name']]=$item;
                }
                $pay_states=['待复核','已复核','已结算'];
                $finishCountList=arrayByKey($finishCountList,'order_id');
                foreach ($list as $k=>&$vinfo){
                    $last_confirm_process_price=db('user_process up')
                        ->join('order o', 'up.order_id = o.id','left')
                        ->where([['o.sku','eq',$vinfo['sku']],['process_name','eq',$vinfo['process_name']],['check_state','>=','2'],["work_time",'<',strtotime(date("Y-m-01 00:00",$vinfo['work_time']))]])->value("process_price");
                    $orderinfo=db("order")->find($vinfo['order_id']);
                    //$skuinfo=db("sku")->where("sku='".$orderinfo['sku']."'")->find(); 去掉图片的显示 节省流量及加速显示列表
                    $vinfo['client_ordernum']=$orderinfo['client_ordernum'];
                    $vinfo['quantity']=$orderinfo['quantity'];
                    $vinfo['last_confirm_process_price']=$last_confirm_process_price==''?'--':$last_confirm_process_price; //上次结算价
                    $vinfo['order_count']=@$finishCountList[$vinfo['order_id']]; //实裁数车间数
                    //$vinfo['stock_count']=isset($inStockList[$vinfo['client_ordernum']]) ? $inStockList[$vinfo['client_ordernum']]['available_count'] :0 ;
                    $vinfo['stock_count']=!empty($vinfo['available_count']) ? $vinfo['available_count'] :0 ;
                    $vinfo['available_checkout_count']=!empty($vinfo['available_checkout_count']) ? $vinfo['available_checkout_count'] :0 ;
                    $vinfo['sew_cut_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['sew_cut_count'] : 0;
                    $vinfo['process_count']=@$processCountList[$vinfo['order_id'].$vinfo['process_name']]['tot_quintity']; //累计结算数
                    $vinfo['tot_process_quintity']=@$processCountList[$vinfo['order_id'].$vinfo['process_name']]['process_quintity']; //累计加工数
                    if (!$export) $vinfo['process_name_json']=json_encode(db('user_process up')->where([['order_id', 'eq', $vinfo['order_id']],['process_stage', 'eq', $process_stage]])
                        ->field("distinct process_name,process_price")->select());
                    $vinfo['money_total']=sprintf('%.2f',$vinfo['tot_quintity']*$vinfo['process_price']);
                    if($status==3) $vinfo['process_total_money']=sprintf("%.2f",$vinfo['process_total_money']);
                    $vinfo['shicai_count']=isset($finishCountList[$vinfo['order_id']]['shicai_count']) ? $finishCountList[$vinfo['order_id']]['shicai_count'] : 0;
                    $vinfo['jiaohuo_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['jiaohuo_count'] : 0;
                    $vinfo['money_total']=$status==3 ? sprintf("%.2f",$vinfo['process_total_money']) : $vinfo['money_total'];
                    $list[$k]['work_time'] =  date('m-d H:i', $list[$k]['work_time']);//出货时间
                    $list[$k]['scan_date'] =  date('m-d H:i', $list[$k]['scan_date']);//出货时间
                    $list[$k]['store_time']= !empty($list[$k]['store_time']) ? date('m-d', $list[$k]['store_time']) : '';//入仓时间
                    //$vinfo['pic_res'] = trim($skuinfo['ori_pic']) == '' ? $skuinfo['pic'] : $skuinfo['ori_pic'];
                    $vinfo['creater_name'] = $vinfo['creater'] >0  ? $systemUserKV[$vinfo['creater']] : '--';
                    $vinfo['check_user'] = $vinfo['check_user'] >0  ? $systemUserKV[$vinfo['check_user']] : '';
                    $vinfo['recheck_user'] = $vinfo['recheck_user'] >0  ? $systemUserKV[$vinfo['recheck_user']] : '--';
                    $vinfo['f_check_date'] = $vinfo['f_check_date'] >0  ? "<br>".date("m-d H:i",$vinfo['f_check_date']) : '';
                    $vinfo['delivery_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['delivery_count'] : 0;
                    $vinfo['pay_count']=$vinfo['store_count']+$vinfo['stock_count'];
                    $vinfo['count_diff']=$vinfo['store_count']+$vinfo['stock_count']+$vinfo['broke_make_count']-$vinfo['process_count']-$vinfo['available_checkout_count']-$vinfo['broke_cost_count'];
                    $vinfo['broke_diff']=$vinfo['broke_make_count']-$vinfo['broke_cost_count'];
                    $vinfo['action_status']=$status;
                    $vinfo['pay_state']=$pay_states[$vinfo['pay_state']];
                    if(!$export && $vinfo['count_diff']<0 && $status<2){ //入仓不足结算数量 待对帐的进行更新
                        $changeWhere=[];
                        $changeWhere[]=['user_number','=',$vinfo['user_number']];$changeWhere[]=['check_state','=',$status-1];
                        $changeWhere[]=['order_id','=',$vinfo['order_id']];
                        $changeWhere[]=['process_name','=',$vinfo['process_name']];
                        $changeWhere[]=['process_stage','=',$process_stage];
                        //$this->updatePayCount($changeWhere,$vinfo['count_diff']);
                    }
                }
            }
            if ($export) {//导出
                $factoryname=empty($factoryId) ? '' : $factoryId;
                    $this->_exportEmployeeSalaryXls('工价核对-' .date('m-d').$factoryname, $list);
                exit;
            }
            //$needcheckCount=$total;
            $reCheckCount=db('user_process up')->where(['check_state' =>2,'process_stage'=>$process_stage])->where($where)
                ->join('order o', 'up.order_id = o.id','left')
                ->group("user_number,pay_state,pay_code,FROM_UNIXTIME(work_time,'%Y-%m')")->count();

            //if(isset($countdata)) $list[]=$countdata;
            $data['data'] = $list;
            $data['needcheckCount'] = $needcheckCount;
            $data['checkedCount'] = $checkedCount;
            $data['reCheckCount'] = $reCheckCount;
            $data['status']=$status;
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $allFactorys=db('user_process up')->where([['process_stage', 'eq', $process_stage]])->field("distinct factory_name")->select();
        $factoryKV=[];
        foreach($allFactorys as $key=>$info){
            $factoryKV[$info['factory_name']]=$info['factory_name'];
        }
        $billmonth=[];
        for($index=-1;$index<6;$index++){
            $monthval=-$index;
            $billmonth[date('Y-m',strtotime("$monthval month"))]=date('Y-m',strtotime("$monthval month"));
        }
        $assign = [
            'overtime_range'=>date("Y-m-d",$startTime1).' ~ '.date('Y-m-04',$endTime1),
            'billmonth'=>$billmonth,'select_month'=>date("Y-m",strtotime("-1 month")),
            'process_stage'=>$process_stage,
            'status'=>$status,
            'factoryKV' => ['' => '请选择'] + $factoryKV
        ];
        return $this->assign($assign)->fetch();
    }

    //$countDiff 库存差异少掉的件数
    private function updatePayCount($dataWehre,$countDiff){
        $countDiff=abs($countDiff);
        $list = db('user_process up')->where($dataWehre)->where("quintity > 0")->order("quintity desc")->select();
        foreach ($list as $key=>$processinfo){
            $maxCanCancel=$processinfo['quintity'] > $countDiff ? $countDiff : $processinfo['quintity']; //可取消掉的最大结算数量
            $changedQuantity=$processinfo['quintity']-$maxCanCancel;
            $ret=db("user_process")->where([['id', 'eq', $processinfo['id']]])->update(['quintity'=>$changedQuantity]);
            $countDiff-=$maxCanCancel;
            if($countDiff<=0){
                break;
            }
        }
    }

    /**
     *复合对账-账单明细
     * @author: sparkguo
     * @Date: 2022/12/2 13:56
     */
    public function salaryDetailList(){
        $month=$this->request->param('month', '');
        $orderid=$this->request->param('order_id', '');
        $user_number=$this->request->param('user_number', '');
        $process_name=$this->request->param('process_name', '');
        $client_ordernum=$this->request->param('client_ordernum', '');
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $export     = $this->request->param('export/d', 0);
        $sku = $this->request->param('sku', '');
        $action_status=$this->request->param('status/d', 3);
        $show_data=$this->request->param('show_data', '');//累计加工数 ，已结算数，扫菲明细/结算数，帐单明细(考虑合并扎号)，process_data,payed_data,scan_data,salary_data,
        if ($this->request->isAjax()|| $this->request->param('export')) {
            $systemUserKV = getSystemUserKV(null);
            list($startTime, $endTime) =  [strtotime(date($month."-01 00:00:00")),strtotime(date("Y-m-t 23:59:59",strtotime($month.'-01 23:59:59')))];
            $where[] = ['up.work_time', 'between', [$startTime, $endTime]];
            $where[]=['user_number','=',$user_number];
            $where[]=['check_state','=',2];
            if(!empty($process_name)){
                $where[] = ['up.process_name', '=', $process_name];
            }
            if(!empty($client_ordernum)){
                $where[] = ['up.order_id', '=',  db('order o')->where([['client_ordernum','eq',$client_ordernum]])->value("id",-1)];
            }
            if(!empty($sku)){
                $where[] = ['up.order_id', 'in',  db('order o')->where([['sku','eq',$sku]])->column("id")];
            }
            $total = db('user_process up')->where($where)->join('order o', 'up.order_id = o.id','left')
                ->group('order_id,process_name')
                ->count();
            $list = db('user_process up')
                ->join('order o', 'up.order_id = o.id','left')
                ->where($where)->page($page)
                ->field("up.*,o.sku,o.client_ordernum,o.quantity as quantity,up.id as id,sum(up.quintity) as tot_quintity,sum(up.process_quintity) as process_quintity,up.order_id as order_id,
                    FROM_UNIXTIME(work_time,'%Y-%m') as month,o.store_time")
                ->limit($limit)
                ->group('order_id,process_name')->select();
            if($total>0){
                //实裁数 车间交货数
                $finishCountList =db('order_size osize')->where([ ['order_id', 'in', array_column($list,'order_id')]])
                    ->field("order_id,sum(osize.shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(sew_cut_count) as sew_cut_count")
                    ->group('order_id')->select();
                $finishCountList=arrayByKey($finishCountList,'order_id');
                //累计加工数
                $processCountRet=db('user_process up')->where([['order_id', 'in', array_column($list,'order_id')]])
                    ->field("*,sum(up.quintity) as tot_quintity,up.id as id")
                    ->group('order_id,process_name')->select();
                $processCountList=[]; //各订单工序 累计加工数数组
                foreach ($processCountRet as $key => $item) {
                    $processCountList[$item['order_id'].$item['process_name']]=$item;
                }
                foreach ($list as $k=>&$vinfo){
                    $vinfo['order_count']=@$finishCountList[$vinfo['order_id']]; //实裁数车间数
                    $vinfo['sew_cut_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['sew_cut_count'] : 0;
                    $vinfo['process_price']=$vinfo['process_price'];
                    $vinfo['jiaohuo_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['jiaohuo_count'] : 0;
                    $vinfo['shicai_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['shicai_count'] : 0;
                    $vinfo['process_count']=@$processCountList[$vinfo['order_id'].$vinfo['process_name']]['tot_quintity'];
                    $vinfo['money_total']=sprintf('%.2f',$vinfo['tot_quintity']*$vinfo['process_price']);
                    $vinfo['last_editer']=!empty($vinfo['last_editer']) ? $systemUserKV[$vinfo['last_editer']] : '';
                    //$list[$k]['work_time'] =  date('Y-m-d H:i', $list[$k]['work_time']);//出货时间
                }
                //总计数据
                $countdata=db('user_process up')->where($where)
                    ->field("sum(up.quintity) as tot_quintity,sum(process_quintity) as process_quintity,sum(quintity * process_price ) as money_total,
                    '总计'as work_time,'' as user_name,'' as user_number,'' as bar_num,'' as shicai_count,'' as flag_only")
                    ->find();
                $countdata['process_count']=$countdata['tot_quintity'];
                $countdata['money_total']=sprintf('%.2f',$countdata['money_total']);
                $list[]=$countdata;

            }
            $data = [];
            $data['data'] = $list;
            if ($export) {//导出
                $this->exportSkuStockXls('成衣库存列表-' .date('YmdHis'), $data['data']);
                exit;
            }
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $assign['action_status']=$action_status;
        $assign['show_data']=$show_data;
        $assign['order_id']=$orderid;
        $assign['user_number']=$user_number;
        $assign['process_name']=$process_name;
        $assign['month']=$month;
        return $this->assign($assign)->fetch("salary_detail_list");
    }


    /**
     *批量处理结算数差异
     * @author: sparkguo
     * @Date: 2022/12/3 9:39
     */
    public function changeDiffCount(){
        $state = $this->request->param('status/d', 1);
        $ids = $this->request->param('id', []);
        $action=$this->request->param('action', '');
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        //--- 开始审核账单到对账中
        $orderids=[];
        $list=db('user_process up')->where([['id', 'in', $ids]])->group('up.order_id,up.process_name')->select();
        $whereSql="";
        foreach ($list as $k=>$v){
            $whereSql.=" (up.order_id={$v['order_id']} and up.process_name='{$v['process_name']}') or";
            $orderids[]=$v['order_id'];
        }
        $whereSql=trim($whereSql,'or');
        $instockRet=db("sku_stock_log log")
            ->field("sum(available_count) as available_count,log.factory_id,log.client_ordernum")//+defective_count
            ->where('action_type','eq',1)->group("log.client_ordernum")->buildSql();
        //出库其它单库存数统计
        $checkOutStockRet=db("sku_stock_log log")
            ->field("sum(available_count) as available_checkout_count,log.out_ordernum,log.client_ordernum")
            ->where('action_type','eq',2)->group("log.out_ordernum")->buildSql();

        $processCountRet=db('user_process up')->field("store_count as store_count2,up.order_id,process_name,sum(up.quintity) as tot_quintity2,up.id as id,sum(process_quintity) as process_quintity2,
        (CASE  WHEN up23.available_count IS NULL THEN 0 ELSE up23.available_count END) as available_count,
        (CASE  WHEN upexp.broke_make_count IS NULL THEN 0 ELSE upexp.broke_make_count END) as broke_make_count,
        (CASE  WHEN outstock.available_checkout_count IS NULL THEN 0 ELSE outstock.available_checkout_count END) as available_checkout_count")
            ->join('order o', 'up.order_id = o.id','left')
            ->join('user_process_ext upexp', 'up.order_id = upexp.order_id','left')
            ->join([$instockRet=> 'up23'], 'o.client_ordernum = up23.client_ordernum','left')
            ->join([$checkOutStockRet=> 'outstock'], 'o.client_ordernum = outstock.out_ordernum','left')
            ->group('order_id,process_name')->buildSql();
        $sqlwhere='';$joinType='inner';
        $sqlwhere .=" and ABS((up2.available_count+up2.store_count2-available_checkout_count) - tot_quintity2) > 0";
        $orderPorcessCountRet = db('user_process up')
            ->join('order o', 'up.order_id = o.id','left')
            ->join([$processCountRet=> 'up2'], 'up.order_id = up2.order_id and up.process_name=up2.process_name'.$sqlwhere,$joinType)
            ->where($whereSql)->field("up.order_id as order_id,up.process_name as process_name,o.client_ordernum,
            (up2.available_count+up2.store_count2+up2.broke_make_count-available_checkout_count) - tot_quintity2 as diff_count,
                    sum(up.quintity) as tot_quintity,group_concat(up.check_remark SEPARATOR '') as check_remark,
                    sum(up.process_quintity) as process_quintity,up.id as id")
            ->group('up.order_id,up.process_name')->select();
        $errOrderPorcessCount=[];
        $jumpinfo='';
        //获取订单及工序纬度的差异数 做循环，超过值(-15以上，>0)的不处理
        foreach ($orderPorcessCountRet as $key=>$val){
            $errOrderPorcessCount[$val['order_id'].$val['process_name']]=$val;
            if($val['diff_count']>=0 || $val['diff_count']< -15){
                $jumpinfo.=$val['client_ordernum'].$val['process_name']."-差数:".$val['diff_count']."，";
                continue;
            }
            //查询该工序的所有参与人，数量大到小排序,，判断key值是否大于等于余数，是则只减基数，不是则减基数+1
            $processTotalRet=db('user_process up')->where([['order_id', '=', $val['order_id']],['is_disabled','=',0],['process_name', '=', $val['process_name']]])
                ->field("*,sum(up.quintity) as tot_quintity")
                ->group('up.order_id,up.process_name,up.user_number')->buildSql();
            $processList=db('user_process up')->where([['up23.order_id', '=', $val['order_id']],['up23.is_disabled','=',0],['up23.process_name', '=', $val['process_name']]])
                            ->join([$processTotalRet=> 'up23'], 'up.id = up23.id','left')
                ->field("up23.*")->order("up23.tot_quintity desc")
                ->select();

            $makeMemberTotal=count($processList);
            if($makeMemberTotal<=0) continue;
            $basicQuantity=Ceil($val['diff_count']/$makeMemberTotal); //最少减数
            $overQuantity=abs($val['diff_count']%$makeMemberTotal); //余数
            foreach ($processList as $index=>$processinfo){
                $set_quantity= $index < $overQuantity && $overQuantity>0 ? $basicQuantity-1 : $basicQuantity;
                $insertData = [
                    'bar_num'=>0,
                    'process_quintity'=>0,
                    'quintity' => $set_quantity,
                    'check_remark' => '',
                    'flag_only'=>0,
                    'update_date' => date('Y-m-d H:i:s'),
                    'last_editer'=>ADMIN_ID,
                    'creater'=>ADMIN_ID,
                    'create_time' => time(),
                ];
                if($set_quantity==0) continue;  //存在差异2件但5个人同时做这道工序的样例,后面3个人就跳过不用增减数了
                $newInsertData=array_merge($processinfo,$insertData);
                unset($newInsertData['id'],$newInsertData['tot_quintity']);
                $processid = db('user_process')->insertGetId($newInsertData);
            }
        }
        $jumpinfo= $jumpinfo != '' ? $jumpinfo." -16件以上及>0件以上需人工处理" : $jumpinfo;
        return $this->Json(1, '处理成功<br>'.$jumpinfo);

    }
    
    private function _getbilldetails(){
        $month=$this->request->param('month', '');
        $orderid=$this->request->param('order_id', '');
        $user_number=$this->request->param('user_number', '');
        $process_name=$this->request->param('process_name', '');
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $export     = $this->request->param('export/d', 0);
        $action_status=$this->request->param('status/d', 3);
        $show_data=$this->request->param('show_data', '');//累计加工数 ，已结算数，扫菲明细/结算数，帐单明细(考虑合并扎号)，process_data,payed_data,scan_data,salary_data,
        if ($this->request->isAjax()|| $this->request->param('export')) {
            $systemUserKV = getSystemUserKV(null);
            list($startTime, $endTime) =  [strtotime(date($month."-01 00:00:00")),strtotime(date("Y-m-t 23:59:59",strtotime($month.'-01 23:59:59')))];
            if($show_data=='process_data'){ //累计加工数
                $where[]=['order_id','=',$orderid];
                $where[]=['process_name','=',$process_name];
            }elseif($show_data=='payed_data'){ //已结算数

            }elseif($show_data=='salary_data'){ //账单明细
                $where[] = ['up.work_time', 'between', [$startTime, $endTime]];
                $where[]=['user_number','=',$user_number];
                $where[]=['check_state','=',2];
            }else{ //扫菲明细/结算数
                $where[]=['user_number','=',$user_number];
                $where[]=['order_id','=',$orderid];
                if(!empty($process_name)) $where[]=['process_name','=',$process_name];
            }
            $total = db('user_process up')->where($where)->join('order o', 'up.order_id = o.id','left')->count();
            $list = db('user_process up')
                ->join('order o', 'up.order_id = o.id','left')
                ->join('sku sk', 'o.sku = sk.sku','left')
                ->where($where)->page($page)->field("up.*,o.quantity,o.client_ordernum,up.id as id,up.quintity as tot_quintity")
                ->limit($limit)->order('up.bar_num asc,process_name desc')->select();
            if($total>0){
                //实裁数 车间交货数
                $finishCountList =db('order_size osize')->where([ ['order_id', 'in', array_column($list,'order_id')]])
                    ->field("order_id,sum(osize.shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(sew_cut_count) as sew_cut_count")
                    ->group('order_id')->select();
                $finishCountList=arrayByKey($finishCountList,'order_id');
                //累计加工数
                $processCountRet=db('user_process up')->where([['order_id', 'in', array_column($list,'order_id')]])
                    ->field("*,sum(up.quintity) as tot_quintity,up.id as id")
                    ->group('order_id,process_name')->select();
                $processCountList=[]; //各订单工序 累计加工数数组
                foreach ($processCountRet as $key => $item) {
                    $processCountList[$item['order_id'].$item['process_name']]=$item;
                }
                foreach ($list as $k=>&$vinfo){
                    $vinfo['order_count']=@$finishCountList[$vinfo['order_id']]; //实裁数车间数
                    $vinfo['sew_cut_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['sew_cut_count'] : 0;
                    $vinfo['process_price']=$vinfo['process_price'];
                    $vinfo['jiaohuo_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['jiaohuo_count'] : 0;
                    $vinfo['shicai_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['shicai_count'] : 0;
                    $vinfo['process_count']=@$processCountList[$vinfo['order_id'].$vinfo['process_name']]['tot_quintity'];
                    $vinfo['money_total']=sprintf('%.2f',$vinfo['tot_quintity']*$vinfo['process_price']);
                    $vinfo['last_editer']=!empty($vinfo['last_editer']) ? $systemUserKV[$vinfo['last_editer']] : '';
                    //$list[$k]['work_time'] =  date('Y-m-d H:i', $list[$k]['work_time']);//出货时间
                }
                //总计数据
                $countdata=db('user_process up')->where($where)
                    ->field("sum(up.quintity) as tot_quintity,sum(process_quintity) as process_quintity,sum(quintity * process_price ) as money_total,
                    '总计'as work_time,'' as user_name,'' as user_number,'' as bar_num,'' as shicai_count,'' as flag_only")
                    ->find();
                $countdata['process_count']=$countdata['tot_quintity'];
                $countdata['money_total']=sprintf('%.2f',$countdata['money_total']);
                $list[]=$countdata;

            }
            $data = [];
            $data['data'] = $list;
            if ($export) {//导出
                $this->exportSkuStockXls('成衣库存列表-' .date('YmdHis'), $data['data']);
                exit;
            }
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $assign['action_status']=$action_status;
        $assign['show_data']=$show_data;
        $assign['order_id']=$orderid;
        $assign['user_number']=$user_number;
        $assign['process_name']=$process_name;
        $assign['month']=$month;
        return $this->assign($assign)->fetch("billdetails");
    }

    //增加或减少结算数量
    public function addPorcess(){
        $dataid=$this->request->param('id', '');
        $quintity=$this->request->param('add_pay_count', 0);
        $check_remark=$this->request->param('check_remark', '');
        $user_name=$this->request->param('user_name', '');
        $user_number=$this->request->param('user_number', '');
        $remarkAll=$this->request->param('remarkAll', '');
        $user_process_total=$this->request->param('user_process_total', 0);
        $count_pay_total=$this->request->param('count_pay_total', '');
        $process_name=$this->request->param('process_name', '');
        $same_process_change=$this->request->param('same_process_change', '');
        if(empty($user_number)){ //empty($user_name) ||
            return $this->Json(1, '员工编号必须填写');
            //return $this->Json(1, '增减数量为0，未做任何处理');
        }
        $memberInfo=db("user_process")->where("user_number='".$user_number."'")->order("id desc")->find();
        if(empty($memberInfo)){
            return $this->Json(1, '未找到编号为'.$user_number."的员工，请先新增一条员工编号为{$user_number}的加工信息");
        }
        $processdata=db("user_process")->where("id=".$dataid)->find();
        unset($processdata['id']);
        $processdata['flag_only']=0;
        $insertData = [
            'factory_name'=>$memberInfo['factory_name'],
            'user_name'=>$memberInfo['user_name'],
            'user_number'=>$user_number,
            'bar_num'=>0,
            'process_quintity'=>0,
            'quintity' => $quintity,
            'check_remark' => $check_remark,
            'update_date' => date('Y-m-d H:i:s'),
            'last_editer'=>ADMIN_ID,
            'creater'=>ADMIN_ID,
            'create_time' => time(),
        ];
        if($same_process_change=="all"){ //同一订单同工序名称 批量增减数量
            $list = db('user_process up')->field("*")
                ->where([['order_id', 'eq',$processdata['order_id']],['check_state','elt',1],['process_name','=',$process_name]])
                ->group('up.order_id,up.process_name,up.user_number')->order("id")->select();
            foreach ($list as $key=>$item){
                unset($item['id']);
                $insertData['factory_name']=$item['factory_name'];
                $insertData['user_name']=$item['user_name'];
                $insertData['user_number']=$item['user_number'];
                $newInsertData=array_merge($item,$insertData);
                $processid = db('user_process')->insertGetId($newInsertData);
            }
        }else if($count_pay_total=="all"){ //同一订单同工序结算数量 批量增减数量
            $list = db('user_process up')->field("*")
                ->where([['order_id', 'eq',$processdata['order_id']],['check_state','elt',1]])
                ->having("sum(quintity) = $user_process_total")
                ->group('up.order_id,up.process_name,up.user_number')->order("id")->select();
            foreach ($list as $key=>$item){
                unset($item['id']);
                $insertData['factory_name']=$item['factory_name'];
                $insertData['user_name']=$item['user_name'];
                $insertData['user_number']=$item['user_number'];
                $newInsertData=array_merge($item,$insertData);
                $processid = db('user_process')->insertGetId($newInsertData);
            }
        }else{
            if($remarkAll=='all'){ //备注引用到同订单其它工序上
                $list = db('user_process up')->field("id,check_remark,user_name,user_number,process_name")
                    ->where([['order_id', 'eq',$processdata['order_id']],['check_state','elt',1],['user_number','<>',$user_number]])
                    ->group('up.order_id,up.process_name,up.user_number')->order("id")->select();
                foreach ($list as $key=>$item){
                    $ret=db("user_process")->where([['id', 'eq', $item['id']]])->update(['last_editer'=>ADMIN_ID,'check_remark'=>$item['check_remark']." ".$check_remark]);
                }
            }
            $insertData=array_merge($processdata,$insertData);
            $processid = db('user_process')->insertGetId($insertData);
        }
        return $this->Json(1, '数据提交成功');
    }

    //增加工价单
    public function editStatements(){
        $status = $this->request->param('status/d', 1);
        $user_name=$this->request->param('user_name/s', '');
        $process_stage=$this->request->param('process_stage/d', 2); //2车间与尾部对账区别参数,3尾部
        $factoryKV = getFactoryKV(false);
        $systemUserKV = getSystemUserKV(null);
        if ($this->request->isAjax()|| $this->request->param('export')) {
            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $export     = $this->request->param('export/d', 0);
            $factoryId   = $this->request->param('factory_id/s', '');
            $client_ordernum   = $this->request->param('client_ordernum', '');
            $process_name=$this->request->param('process_name', '');
            $sku = $this->request->param('sku', '');
            $overDateRange=$this->request->param('create_date_range');
            list($startTime, $endTime) = $overDateRange != '' ? array_map('strtotime', explode('~', $overDateRange)) : [strtotime(date("Y-m-01 00:00:00",strtotime("-6 month"))),time()];
            $where[]=['process_stage', 'eq', $process_stage];
            //$where[]=['creater', 'gt', 0];
            if(!empty($process_name)){
                $where[]=['process_name','like',"%".$process_name."%"];
            }
            if(!empty($user_name)){
                $where[]=['user_name','like',"%".$user_name."%"];
            }
            if ($export) {
                set_time_limit(0);
                $page = 1;$limit = 99999;
            }
            if($sku) $where[] = ['o.sku', '=', $sku];
            if($client_ordernum) $where[] = ['o.client_ordernum', '=', $client_ordernum];
            if($overDateRange) $where[] = ['up.work_time', 'between', [$startTime, $endTime+86399]];
            if($factoryId) $where[] = ['up.factory_name', '=', $factoryId];

            $total = db('user_process up')->where($where)->join('order o', 'up.order_id = o.id','left')
                ->group('order_id,process_name,user_number')->count();
            $list = db('user_process up')
                ->join('order o', 'up.order_id = o.id','left')
                ->join('sku sk', 'o.sku = sk.sku','left')
                ->where($where)->page($page)->field("*,sum(up.quintity) as tot_quintity,up.id as id")
                ->group('order_id,process_name,user_number')->limit($limit)->order('up.id desc')->select();

            if($total>0){
                //实裁数 车间交货数
                $finishCountList =db('order_size osize')->where([ ['order_id', 'in', array_column($list,'order_id')]])
                    ->field("order_id,sum(osize.shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(sew_cut_count) as sew_cut_count")
                    ->group('order_id')->select();
                $finishCountList=arrayByKey($finishCountList,'order_id');
                //累计加工数
                $processCountRet=db('user_process up')->where([['order_id', 'in', array_column($list,'order_id')]])
                    ->field("*,sum(up.quintity) as tot_quintity,up.id as id")
                    ->group('order_id,process_name')->select();
                $processCountList=[]; //各订单工序 累计加工数数组
                foreach ($processCountRet as $key => $item) {
                    $processCountList[$item['order_id'].$item['process_name']]=$item;
                }
                foreach ($list as $k=>&$vinfo){
                    $vinfo['process_name_json']=json_encode(db('user_process up')->where([['order_id', 'eq', $vinfo['order_id']],['process_stage', 'eq', $process_stage]])->field("distinct process_name,process_price")->select());
                    $vinfo['order_count']=@$finishCountList[$vinfo['order_id']]; //实裁数车间数
                    $vinfo['process_price']=round($vinfo['process_price'],4);
                    $vinfo['shicai_count']=isset($finishCountList[$vinfo['order_id']]['shicai_count']) ? $finishCountList[$vinfo['order_id']]['shicai_count'] : 0;
                    $vinfo['jiaohuo_count']=isset($finishCountList[$vinfo['order_id']]) ? $finishCountList[$vinfo['order_id']]['jiaohuo_count'] : 0;
                    $vinfo['process_count']=@$processCountList[$vinfo['order_id'].$vinfo['process_name']]['tot_quintity'];
                    $vinfo['money_total']=sprintf('%.2f',$vinfo['tot_quintity']*$vinfo['process_price']);
                    //$list[$k]['work_time'] =  date('Y-m-d H:i', $list[$k]['work_time']);//出货时间
                    $vinfo['pic_res'] = trim($vinfo['ori_pic']) == '' ? $vinfo['pic'] : $vinfo['ori_pic'];
                    $vinfo['creater_name'] = $vinfo['creater'] >0  ? $systemUserKV[$vinfo['creater']] : '--';
                }
            }
            $needcheckCount=db('user_process up')->where([['check_state', 'eq', 1],['process_stage', 'eq', $process_stage]])->group('order_id,process_name,user_number')->count();
            $checkedCount=db('user_process up')->where([['check_state', 'gt', 1],['process_stage', 'eq', $process_stage]])->group('order_id,process_name,user_number')->count("id");;

            $data = [];
            $data['data'] = $list;
            if ($export) {//导出
                $this->exportSkuStockXls('成衣库存列表-' .date('YmdHis'), $data['data']);
                exit;
            }
            $data['needcheckCount'] = $needcheckCount;
            $data['checkedCount'] = $checkedCount;
            $data['status']=$status;
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $dataAllFactorys=db('user_process up')->where([['process_stage', 'eq', $process_stage]])->field("distinct factory_name")->select();
        $selectfactoryKV=[];
        foreach($factoryKV as $key=>$info){
            $selectfactoryKV[$info]=$info;
        }
        $processNameList=db('user_process up')->where([['process_stage', 'eq', $process_stage]])->field('distinct process_name')->select();
        $processNameList=array_column($processNameList,'process_name','process_name');
        $assign = [
            'today'=>date("Y-m-d",strtotime("-1 month")),
            'process_stage'=>$process_stage,
            'status'=>$status,
            'factoryKV' => ['' => '请选择'] + $selectfactoryKV
        ];
        $assign['processNameList']=$processNameList;
        return $this->assign($assign)->fetch();
    }

    private function convertDate($dateValue) {
        $unixDate = ($dateValue - 25569) * 86400;
        return strtotime(gmdate("Y-m-d", $unixDate).date(" H:i:s"));
    }

    /*工价导入*/
    public function import(){
        if(isset($_FILES)){
            $orderServise = new OrderService();
            $params = $paramsSz = $paramsOm = $paramsMl = [];
            $params['file_path']=$paramsOm['file_path']=$paramsSz['file_path']=$paramsMl['file_path'] = $_FILES['file']['tmp_name'];
            // 数据开始行（非必须，正常第一行为表头，所以默认值为2）
            $params['start']=$paramsOm['start']=$paramsSz['start'] = $paramsMl['start'] = 1;
            // 模型（表名或模型二选一）
            $params['model']=$paramsOm['model'] = $paramsSz['model']= $paramsMl['model']  = 'cms/content';

            $resultAll = plugins_run('excel/excel/import', $params);
            $chejianProcessNames=['平车','打边','冚车'];
            $weibuProcessNames=['剪线','剪线','大烫','包装','包装','大烫','查货'];
            $weibuProcessNameCount=$chejianProcessNameCount=[];

            if ($resultAll === false) {
                return $this->error('excel读取失败');
            }
            foreach ($resultAll as $keyr => $valuer) {
                foreach ($valuer as $k2 => $v2) {
                    //PHP 清除 Excel 导入的数据空格 https://www.cnblogs.com/xtmp/p/10773662.html
                    if ($k2 == 'N' || $k2 == 'Q') {
                        $resultAll[$keyr][$k2] = trim($v2);//去空格
                    } else {
                        $resultAll[$keyr][$k2] = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", $v2);
                    }
                }
            }
            $process_stage=$this->request->param('process_stage/d', 3);//2车间 3尾部
            $factoryNameVal = db("factory")->column("id","name");

            //检测订单号是否存在，规格、数量、单价、金额 是否数字
            $lossSku=$lossSize=$alreadyOrder=$existDatas=[];
            $result_head=array_shift($resultAll);
            foreach ($resultAll as $index => $pInfo) {
                if (trim($pInfo['A']) == '' &&  trim($pInfo['B'])=="") {
                    return $this->error('excel导入数据名字不能为空，行数'.$index);
                    break;
                }
                $vnewr = [
                    'order_id' => 0,
                    'cut_id' => 0, //床号
                    'bar_num' => 0, //扎号
                    'quintity' => intval($pInfo['H']),
                    'process_stage' => $process_stage,
                    'process_id' => 0,
                    'client_ordernum'=>trim($pInfo['E']),
                    'process_name' => trim($pInfo['F']),
                    'process_price' => floatval($pInfo['G'])*floatval($pInfo['I']),
                    'user_name' => trim($pInfo['B']),
                    'user_number' => trim($pInfo['B']), //用户编号
                    'work_time' => intval($this->convertDate($pInfo['A'])), //完成时间 工资月份
                    'flag_only' => 0,//唯一标识
                    'factory_name' => trim($pInfo['M']),
                    'group_name' => trim($pInfo['C']),
                    'check_remark' => trim($pInfo['K']),
                    'update_date' => date('Y-m-d H:i:s'),
                    'creater'=>ADMIN_ID,
                    'create_time' => time(),
                ];
                //格式过滤--特别是时间
                if (empty($pInfo['A'])) {
                    return $this->error('excel的日期时间读取失败,行数'.$index);
                }
                if($process_stage==3 && in_array($vnewr['process_name'],$chejianProcessNames)){ //检测导入尾部时是否有车间的工序
                    $chejianProcessNameCount[$vnewr['process_name']]=1;
                }
                if (count($chejianProcessNameCount)>=3) {
                    $existDatas='尾部不能导入车间的加工数据,请检查导入列表里是否存在'.implode("，",$chejianProcessNames)." 工序";
                    $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                    return $this->Json(2, '导入失败',$data);
                }
                if (empty($factoryNameVal[$vnewr['factory_name']])) {
                    $factorystr=implode(',',array_keys($factoryNameVal));
                    $existDatas[]='不存在的工厂名称,行数'.($index+1).",数据：".$pInfo['M']."，请确认工厂名称在以下列表里：".$factorystr;
                    $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                    return $this->Json(2, '导入失败',$data);
                }
                $vnewr['user_number']="f".$factoryNameVal[$vnewr['factory_name']]."-".trim($pInfo['B']); //生成员工编号

                if (empty($vnewr['quintity']) || empty($vnewr['process_price']) || empty($vnewr['process_name']) || empty($vnewr['factory_name'])) {
                    $existDatas='数量，价格或规格，工序名称，以及工厂名称不能为空,行数'.($index+1);
                    $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                    return $this->Json(2, '导入失败',$data);
                }
                $result[]=$vnewr;
            }


            $insertData=[];$in_key=1;
            foreach ($result as $key => &$value) {
                $orderInfo=db('order')->where('client_ordernum',$value['client_ordernum'])->field("id,client_ordernum")->findOrEmpty();
                if(!$orderInfo){
                    $alreadyOrder[]=$value['client_ordernum'];
                }else{
                    $value['order_id']=$value['cut_id']=$orderInfo['id'];
                }
                //加工费导入重复判断- 订单号，工厂，名字，工序，数量，单价，
                $haveProcessData=db("user_process")->where([['order_id', 'eq', $value['order_id']],['factory_name', 'eq', $value['factory_name']],['user_name', 'eq', $value['user_name']]
                    ,['process_name', 'eq', $value['process_name']],['quintity', 'eq', $value['quintity']],['process_price', 'eq', $value['process_price']]])
                    ->field("id,client_ordernum")->findOrEmpty();
                if($haveProcessData){
                    $existDatas[]=$value['user_name'].'-'.$value['client_ordernum'].'-'.$value['process_name'].''.$value['quintity'].'个-行数'. ($key+2);
                    unset($result[$key]);continue;
                }
                $insertData[$in_key]=$value;
                $in_key+=1;
                unset($result[$key]);
            }
            if($alreadyOrder!=[]  || $lossSize!=[]){
                $existDatas=array_values(array_unique($existDatas));$lossSize=array_values(array_unique($lossSize));$alreadyOrder=array_values(array_unique($alreadyOrder));
                $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                return $this->Json(2, '导入失败',$data);
            }
            if(count($insertData)<1){
                $existDatas='所导入的数据均已存在，请勿重复导入';
                $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                return $this->Json(2, '导入失败',$data);
            }

            try {
                db()->startTrans();
                    $paramsMl['data'] = $insertData;
                    $paramsMl['table'] = 'user_process';
                    $colnums=array_keys($insertData[1]);$insertColnums=[];
                    foreach ($colnums as $index=>$colnum){
                        $insertColnums[$colnum]=$colnum;
                    }
                    // 列与字段的索引关系（需要自动入库的时候，此参数必须）
                    $paramsMl['fields'] = $insertColnums;
                    $resultMl = plugins_run('excel/excel/import', $paramsMl);
                db()->commit();
                $data=['success_count'=>count($insertData),'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                return $this->Json(1, "导入成功",$data);

            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, "导入失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
            // 导入成功将自动返回新增ID，请自行打印$result查看
        }
    }

    //导入金鹏加工列表数据
    public function  importJPprocess(){
        if(isset($_FILES)){
            $orderServise = new OrderService();
            $params = $paramsSz = $paramsOm = $paramsMl = [];
            $params['file_path']=$paramsOm['file_path']=$paramsSz['file_path']=$paramsMl['file_path'] = $_FILES['file']['tmp_name'];
            // 数据开始行（非必须，正常第一行为表头，所以默认值为2）
            $params['start']=$paramsOm['start']=$paramsSz['start'] = $paramsMl['start'] = 1;
            // 模型（表名或模型二选一）
            $params['model']=$paramsOm['model'] = $paramsSz['model']= $paramsMl['model']  = 'cms/content';

            $resultAll = plugins_run('excel/excel/import', $params);
            $chejianProcessNames=['平车','打边','冚车'];
            $weibuProcessNames=['剪线','剪线','大烫','包装','包装','大烫','查货'];
            $weibuProcessNameCount=$chejianProcessNameCount=[];

            if ($resultAll === false) {
                return $this->error('excel读取失败');
            }

            $process_stage=$this->request->param('process_stage/d', 3);//2车间 3尾部
            $factoryNameVal = db("factory")->column("id","name");

            //检测订单号是否存在，规格、数量、单价、金额 是否数字
            $lossSku=$lossSize=$alreadyOrder=$existDatas=[];
            $result_head=array_shift($resultAll);
            foreach ($resultAll as $index => $pInfo) {
                if (trim($pInfo['A']) == '' &&  trim($pInfo['B'])) {
                    return $this->error('excel导入数据名字不能为空，行数'.$index);
                    break;
                }
                //a员工	b生产组	c款号	d生产单	e工序名	f数量	g单价	h金额     蔡金兰[60692]	尾部	swlegging07191220055	9754014	2.剪线	121	0.21	25.41
                list($user_name,$user_number)=explode('[',$pInfo['A']);
                list($pindex,$processName)=explode('.',$pInfo['E']);
                $user_number=trim($user_number,']');
                $vnewr = [
                    'order_id' => 0,
                    'cut_id' => 0, //床号
                    'bar_num' => 0, //扎号
                    'quintity' => intval($pInfo['F']),
                    'process_stage' => $process_stage,
                    'process_id' => 0,
                    'client_ordernum'=>trim($pInfo['D']),
                    'process_name' => trim($processName),
                    'process_price' => floatval($pInfo['G']),
                    'user_name' => trim($user_name),
                    'user_number' => trim($user_number), //用户编号
                    'work_time' => strtotime(date("2022-09-09 09:09:09")), //完成时间 工资月份
                    'flag_only' => 0,//唯一标识
                    'factory_name' => '草堂针织六厂',
                    'group_name' => trim($pInfo['B']),
                    'check_remark' => '',
                    'update_date' => date('Y-m-d H:i:s'),
                    'creater'=>ADMIN_ID,
                    'create_time' => time(),
                ];
                //格式过滤--特别是时间
                if (empty($pInfo['A'])) {
                    //return $this->error('excel的日期时间读取失败,行数'.$index);
                }
                if($process_stage==3 && in_array($vnewr['process_name'],$chejianProcessNames)){ //检测导入尾部时是否有车间的工序
                    //$chejianProcessNameCount[$vnewr['process_name']]=1;
                    $vnewr['process_stage']=2;
                }
                if (empty($factoryNameVal[$vnewr['factory_name']])) {
                    $factorystr=implode(',',array_keys($factoryNameVal));
                    $existDatas[]='不存在的工厂名称,行数'.($index+1).",数据：".$pInfo['M']."，请确认工厂名称在以下列表里：".$factorystr;
                    $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                    //return $this->Json(2, '导入失败',$data);
                }
                //$vnewr['user_number']="f".$factoryNameVal[$vnewr['factory_name']]."-".trim($pInfo['B']); //生成员工编号

                if (empty($vnewr['quintity']) ||  empty($vnewr['process_name']) || empty($vnewr['factory_name'])) {
                    $existDatas='数量，价格或规格，工序名称，以及工厂名称不能为空,行数'.($index+1);
                    $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                    return $this->Json(2, '导入失败4',$data);
                }
                $result[]=$vnewr;
            }

            $insertData=[];$in_key=1;$alreadyJpNumbers=$insertUsers=[];
            $insertuserKey=1;
            foreach ($result as $key => &$value) {
                $orderInfo=db('order')->where('client_ordernum',$value['client_ordernum'])->field("id,client_ordernum")->findOrEmpty();
                if(!$orderInfo){
                    //$alreadyOrder[]=$value['client_ordernum'];
                    $existDatas[] = $value['user_name'] . '-' . $value['client_ordernum'] . '-' . $value['process_name'] . '' . $value['quintity'] . '个订单号不存在-行数' . ($key + 2);
                    unset($result[$key]);
                    continue;
                }else{
                    $value['order_id']=$value['cut_id']=$orderInfo['id'];
                }
                //`name`='郭浩天',`factory_id`='16',`depart_id`='24',`group_id`='73',`status`='1',`number`='1',`jp_number`='3212',`worktype`='cw,other',`create_time`='1667119238',`update_time`='1667119238'

                $user=[
                    'name'=>$value['user_name'],'factory_id'=>'16','depart_id'=>'24','group_id'=>'73','status'=>'1',
                    'number'=>'1','jp_number'=>$value['user_number'],'worktype'=>'cw,other','create_time'=>time(),'update_time'=>time()
                ];
                if(!in_array($value['user_number'],$alreadyJpNumbers)){
                    $insertUsers[$insertuserKey]=$user;
                    $insertuserKey+=1;
                }
                $alreadyJpNumbers[]=$value['user_number'];

                //加工费导入重复判断- 订单号，工厂，名字，工序，数量，单价，
                $haveProcessData=db("user_process")->where([['order_id', 'eq', $value['order_id']],['factory_name', 'eq', $value['factory_name']],['user_name', 'eq', $value['user_name']]
                    ,['process_name', 'eq', $value['process_name']]])->field("id,client_ordernum,sum(quintity) as quintity")
                    ->findOrEmpty();//,['quintity', 'eq', $value['quintity']],['process_price', 'eq', $value['process_price']]
                if($haveProcessData){
                    if(abs($value['quintity'] - $haveProcessData['quintity'])<=25) {
                        $existDatas[] = $value['user_name'] . '-' . $value['client_ordernum'] . '-' . $value['process_name'] . '' . $value['quintity'] . '个-行数' . ($key + 2);
                        unset($result[$key]);
                        continue;
                    }
                }
                //生成会员编号
                /*$haveProcessData=db("user_process")->where([['factory_name', 'eq', $value['factory_name']],['user_number', 'neq', ''],['user_name', 'eq', $value['user_name']]])
                    ->field("id,client_ordernum,user_number")->order("id asc")->findOrEmpty();
                if ($haveProcessData) {
                    $vnewr['user_number']=$haveProcessData['user_number'];
                }*/
                //去掉已经结算的
                $payedProcessData=db("user_process_payed")->where([['order_id', 'eq', $value['order_id']],['factory_name', 'eq', $value['factory_name']],['user_name', 'eq', $value['user_name']]
                    ,['process_name', 'eq', $value['process_name']]])
                    ->field("id,client_ordernum,quintity")->findOrEmpty();
                if($payedProcessData){
                    if(abs($value['quintity'] - $payedProcessData['quintity'])<=20 ){ //差数在23以内  不新增记录
                        $existDatas[]=$value['user_name'].'-'.$value['client_ordernum'].'-'.$value['process_name'].''.$value['quintity'].'个已结算-行数'. ($key+2);
                        unset($result[$key]);continue;
                    }
                    $value['check_remark'].=" 已结".$payedProcessData['quintity'].'个';
                }

                $insertData[$in_key]=$value;
                $in_key+=1;
                unset($result[$key]);
            }
            if($alreadyOrder!=[]  || $lossSize!=[]){
                $existDatas=array_values(array_unique($existDatas));$lossSize=array_values(array_unique($lossSize));$alreadyOrder=array_values(array_unique($alreadyOrder));
                $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                return $this->Json(2, '导入失败2',$data);
            }
            if(count($insertData)<1){
                $existDatas='所导入的数据均已存在，请勿重复导入';
                $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                return $this->Json(2, '导入失败3',$data);
            }

            try {
                db()->startTrans();
                $paramsMl['data'] = $insertData;
                $paramsMl['table'] = 'user_process';
                $colnums=array_keys($insertData[1]);$insertColnums=[];
                foreach ($colnums as $index=>$colnum){
                    $insertColnums[$colnum]=$colnum;
                }
                // 列与字段的索引关系（需要自动入库的时候，此参数必须）
                $paramsMl['fields'] = $insertColnums;
                //$resultMl = plugins_run('excel/excel/import', $paramsMl);
                //============= 增加会员帐号
                $paramsSz['data'] = $insertUsers;
                $paramsSz['table'] = 'user';
                $colnums=array_keys($insertUsers[1]);$insertColnums=[];
                foreach ($colnums as $index=>$colnum){
                    $insertColnums[$colnum]=$colnum;
                }
                // 列与字段的索引关系（需要自动入库的时候，此参数必须）
                $paramsSz['fields'] = $insertColnums;
                //$resultMl = plugins_run('excel/excel/import', $paramsSz);


                db()->commit();
                $data=['success_count'=>count($insertData),'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                return $this->Json(1, "导入成功",$data);

            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, "导入失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
            // 导入成功将自动返回新增ID，请自行打印$result查看
        }
        return $this->Json(1, "金鹏加工导入成功");
    }

    //导入成本报损数
    public function importCostBroke(){
        $params = $paramsSz = $paramsOm = $paramsMl = [];
        $params['file_path']=$paramsOm['file_path']=$paramsSz['file_path']=$paramsMl['file_path'] = $_FILES['file']['tmp_name'];
        // 数据开始行（非必须，正常第一行为表头，所以默认值为2）
        $params['start']=$paramsOm['start']=$paramsSz['start'] = $paramsMl['start'] = 2;
        // 模型（表名或模型二选一）
        $params['model']=$paramsOm['model'] = $paramsSz['model']= $paramsMl['model']  = 'cms/content';

        $resultAll = plugins_run('excel/excel/import', $params);
        if ($resultAll === false) {
            return $this->error('excel读取失败');
        }

        $lossSku=$lossSize=$alreadyOrder=$existDatas=$alreadyJpNumbers=[];
        $insertuserKey=1;
        $result_head=array_shift($resultAll);
        $imp_ordernums=array_column($resultAll,'A');
        //查询所有导入订单号的对应订单id, 订单号下标数组排列 8983021] => 111436 [9025912] => 111988
        $orderDataList=db('order')->where([['client_ordernum','in',$imp_ordernums]])->column("id",'client_ordernum');
        $existBrokeOrder=db('user_process_ext')->where([['order_id','in',$orderDataList]])->column("id",'order_id');

        //查询扩展表已经存在的订单号数据，存在则更新，并在导入数据里过滤掉这条插入；
        foreach ($resultAll as $index => $pInfo) {
            if (trim($pInfo['A']) == '' && trim($pInfo['B'])) {
                return $this->error('excel导入数据订单号不能为空，行数' . $index);
                break;
            }
            //  a订单号	b报损件数	c日期
            $user = [
                'client_ordernum'=>$pInfo['A'],
                'last_editer'=>ADMIN_ID,
                'order_id' => $orderDataList[$pInfo['A']], 'broke_cost_count' => $pInfo['B'], 'create_time' => time()
            ];
            if (in_array($user['order_id'], $existBrokeOrder)) {  //已存在报损数 更新 报损数
                $processid = db('user_process_ext')->where(['order_id'=>$user['order_id']])->update(['broke_cost_count' => $user['broke_cost_count']]);
            }else{
                $insertUsers[$insertuserKey] = $user;
                $insertuserKey += 1;
            }
        }
        if(count($insertUsers)<1){
            return $this->Json(1, "报损数已导入成功");
        }
        $colnums=array_keys($insertUsers[1]);$insertColnums=[];
        foreach ($colnums as $index=>$colnum){
            $insertColnums[$colnum]=$colnum;
        }
        //============= 增加断码数据
        $paramsSz['data'] = $insertUsers;
        $paramsSz['table'] = 'user_process_ext';
        $colnums=array_keys($insertUsers[1]);$insertColnums=[];
        foreach ($colnums as $index=>$colnum){
            $insertColnums[$colnum]=$colnum;
        }
        // 列与字段的索引关系（需要自动入库的时候，此参数必须）
        $paramsSz['fields'] = $insertColnums;
        $resultMl = plugins_run('excel/excel/import', $paramsSz);
        return $this->Json(1, "报损数已导入成功");
    }

    //导入已结算工价列表
    public function importPayedProcess(){
        if(isset($_FILES)){
            $orderServise = new OrderService();
            $params = $paramsSz = $paramsOm = $paramsMl = [];
            $params['file_path']=$paramsOm['file_path']=$paramsSz['file_path']=$paramsMl['file_path'] = $_FILES['file']['tmp_name'];
            // 数据开始行（非必须，正常第一行为表头，所以默认值为2）
            $params['start']=$paramsOm['start']=$paramsSz['start'] = $paramsMl['start'] = 1;
            // 模型（表名或模型二选一）
            $params['model']=$paramsOm['model'] = $paramsSz['model']= $paramsMl['model']  = 'cms/content';

            $resultAll = plugins_run('excel/excel/import', $params);
            $chejianProcessNames=['平车','打边','冚车'];
            //a日期  b姓名	c组别	d SKU	e订单号	f工序	规格	h数量	i单价	j金额	k备注	l库存	m工厂-
            if ($resultAll === false) {
                return $this->error('excel读取失败');
            }

            $process_stage=$this->request->param('process_stage/d', 3);//2车间 3尾部
            $factoryNameVal = db("factory")->column("id","name");

            //检测订单号是否存在，规格、数量、单价、金额 是否数字
            $lossSku=$lossSize=$alreadyOrder=$existDatas=[];
            $result_head=array_shift($resultAll);
            foreach ($resultAll as $index => $pInfo) {
                if (trim($pInfo['A']) == '' &&  trim($pInfo['B'])=='') {
                    print_r($pInfo);
                    return $this->error('excel导入数据名字不能为空，行数'.$index);
                    break;
                }
                //strtotime(date("2022-09-09 09:09:10")), //完成时间 工资月份
                $vnewr = [
                    'order_id' => 0,
                    'cut_id' => 0, //床号
                    'bar_num' => 0, //扎号
                    'quintity' => floatval($pInfo['H']),
                    'process_stage' => $process_stage,
                    'process_id' => 0,
                    'client_ordernum'=>trim($pInfo['E']),
                    'process_name' => trim($pInfo['F']),
                    'process_price' => floatval($pInfo['G'])*floatval($pInfo['I']),
                    'user_name' => trim($pInfo['B']),
                    'user_number' => trim($pInfo['B']), //用户编号
                    'work_time' => strtotime(date("2022-08-09 09:09:10")), //完成时间 工资月份
                    'flag_only' => 0,//唯一标识
                    'factory_name' => trim($pInfo['M']),
                    'group_name' => trim($pInfo['C']),
                    'check_remark' => trim($pInfo['K']),
                    'update_date' => date('Y-m-d H:i:s'),
                    'creater'=>ADMIN_ID,
                    'create_time' => time(),
                ];
                //格式过滤--特别是时间
                if (empty($pInfo['A'])) {
                    //return $this->error('excel的日期时间读取失败,行数'.$index);
                }
                if($process_stage==3 && in_array($vnewr['process_name'],$chejianProcessNames)){ //检测导入尾部时是否有车间的工序
                    $chejianProcessNameCount[$vnewr['process_name']]=1;
                }

                if (empty($factoryNameVal[$vnewr['factory_name']])) {
                    $factorystr=implode(',',array_keys($factoryNameVal));
                    $existDatas[]='不存在的工厂名称,行数'.($index+1).",数据：".$pInfo['M']."，请确认工厂名称在以下列表里：".$factorystr;
                    $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                    return $this->Json(2, '导入失败',$data);
                }
                $vnewr['user_number']="f".$factoryNameVal[$vnewr['factory_name']]."-".trim($pInfo['B']); //生成员工编号

                if (empty($vnewr['quintity']) || empty($vnewr['process_name']) || empty($vnewr['factory_name'])) {
                    $existDatas='数量，工序名称，以及工厂名称不能为空,行数'.($index+1).json_encode($vnewr);
                    $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                    return $this->Json(2, '导入失败',$data);
                }
                $result[]=$vnewr;
            }


            $insertData=[];$in_key=1;
            foreach ($result as $key => &$value) {
                $orderInfo=db('order')->where('client_ordernum',$value['client_ordernum'])->field("id,client_ordernum")->findOrEmpty();
                if(!$orderInfo){
                    $alreadyOrder[]=$value['client_ordernum'];
                }else{
                    $value['order_id']=$value['cut_id']=$orderInfo['id'];
                }
                //加工费导入重复判断- 订单号，工厂，名字，工序，数量，单价，
                $haveProcessData=db("user_process_payed")->where([['order_id', 'eq', $value['order_id']],['factory_name', 'eq', $value['factory_name']],['user_name', 'eq', $value['user_name']]
                    ,['process_name', 'eq', $value['process_name']],['quintity', 'eq', $value['quintity']],['process_price', 'eq', $value['process_price']]])
                    ->field("id,client_ordernum")->findOrEmpty();
                if($haveProcessData){
                    $existDatas[]=$value['user_name'].'-'.$value['client_ordernum'].'-'.$value['process_name'].''.$value['quintity'].'个-行数'. ($key+2);
                    //unset($result[$key]);continue;
                }
                $insertData[$in_key]=$value;
                $in_key+=1;
                unset($result[$key]);
            }
            if(count($insertData)<1){
                $existDatas='所导入的数据均已存在，请勿重复导入';
                $data=['order'=>$alreadyOrder,'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                return $this->Json(2, '导入失败',$data);
            }
            try {
                db()->startTrans();
                $paramsMl['data'] = $insertData;
                $paramsMl['table'] = 'user_process_payed';
                $colnums=array_keys($insertData[1]);$insertColnums=[];
                foreach ($colnums as $index=>$colnum){
                    $insertColnums[$colnum]=$colnum;
                }
                // 列与字段的索引关系（需要自动入库的时候，此参数必须）
                $paramsMl['fields'] = $insertColnums;
                $resultMl = plugins_run('excel/excel/import', $paramsMl);
                db()->commit();
                echo '1111';
                $data=['success_count'=>count($insertData),'sku'=>$lossSku,'existdata'=>$existDatas,'size'=>$lossSize];
                return $this->Json(1, "已结算导入成功",$data);

            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, "导入失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
            // 导入成功将自动返回新增ID，请自行打印$result查看
        }
        return $this->Json(1, "已结算导入成功");
    }

    //增加工价单
    public function addBills(){
        $action=$this->request->param('action', '');
        $postdata=$_POST;
        if($action==''){
            $havsMember=db('user_process up')->where(['user_number'=>$postdata['user_number']])->find();
            if(empty($havsMember) && $postdata['employee_is_along']==1){
                $this->error('没有对应编号的职员');
            }
            $havsOrder=db('order')->where(['client_ordernum'=>$postdata['client_ordernum']])->value('id');
            if(empty($havsOrder)){
                $this->error('没有找到对应订单号订单');
            }
            unset($postdata['delivery_status']);unset($postdata['url']);
            $insData = $postdata;
            if($postdata['employee_is_along']==0){//临时工处理
                if(empty($postdata['factory_name'])){
                    $this->error('没有选择加工单所属工厂');
                }
                $haveNotAlongUinfo=db('user_process up')->where("user_number like 'n%'")->order('id desc')->find();
                if($haveNotAlongUinfo){
                    $insUserNumber=substr($haveNotAlongUinfo['user_number'],1)+1;
                    $insUserNumber=$insUserNumber<10 ? "n0".$insUserNumber : "n".$insUserNumber;
                }else{
                    $insUserNumber="n01";
                }
                $insData['user_name']=$postdata['user_number'];
                $insData['user_number']=$insUserNumber;
                $insData['group_name']='--';
                unset($insData['employee_is_along']);
            }else{
                unset($insData['employee_is_along']);
                $insData['user_name']=$havsMember['user_name'];
                $insData['factory_name']=$havsMember['factory_name'];
                $insData['group_name']=$havsMember['group_name'];
            }
            $insData['process_quintity']=$postdata['quintity'];
            $insData['process_stage']=$postdata['process_stage'];
            $insData['order_id']=$havsOrder;
            $insData['creater']=ADMIN_ID;
            $insData['create_time']=time();
            $insData['work_time']=strtotime($insData['work_time']);
            $processid = db('user_process')->insertGetId($insData);
            return $this->Json(1, '数据新增成功');
        }else if($action=='delete'){
            $sfInfo=db('order')->where(['id'=>$postdata['id']])->find();
            //删除入单信息
            db('user_process')->where('id', $postdata['id'])->delete();
            $this->addOrderLog($sfInfo['id'], $sfInfo['client_ordernum'], "车尾工价结算操作 删除一个人工入单信息");
            return $this->Json(1, '删除成功');
        }else{
            $editdata = $postdata;
            $editdata['work_time']=strtotime($editdata['work_time']);
            unset($editdata['action']);unset($editdata['action_event']);
            $processid = db('user_process')->where(['id'=>$editdata['id']])->update($editdata);
            return $this->Json(1, '编辑成功');
        }

    }

    //审核车间或尾部账单
    public function statementsCheck(){
        $state = $this->request->param('status/d', 1);
        $ids = $this->request->param('id', []);
        $action=$this->request->param('action', '');
        if($action=='deleteProcess'){ //删除作废或多余同步的加工信息
            $orderid=$this->request->param('orderid', '');
            $memberNumber=$this->request->param('memberid', '');
            $dataid=$this->request->param('dataid', '');
            $process_name=$this->request->param('process_name', '');
            //'order_id,process_name,user_number'
            if(empty($orderid) || empty($memberNumber) || empty($memberNumber)) {
                return $this->Json(102, '缺少用户编号与订单编号');
            }
            $delWhere=[['order_id', 'eq', $orderid],['process_name', 'eq', $process_name],['user_number', 'eq', $memberNumber]];
            if(!empty($dataid)) {
                $delWhere[]=['id', 'eq', $dataid];
            }
            $list=db('user_process')->where($delWhere)->delete();
            return $this->Json(1, '删除成功');
        }
        //批量处理件数差异
        if($action=='changeDiffCount'){
            return $this->changeDiffCount();
        }
        if($action=='setBrokeAndNote'){  //设置报损数量与备注
            $orderid=$this->request->param('orderid', '');
            $memberNumber=$this->request->param('memberid', '');
            $dataid=$this->request->param('dataid', '');
            $process_name=$this->request->param('process_name', '');
            $process_remark=$this->request->param('process_remark', '');
            $broke_count=$this->request->param('broke_count', 0);
            //'order_id,process_name,user_number'
            if(empty($orderid) || empty($memberNumber) || empty($memberNumber)) {
                return $this->Json(102, '缺少用户编号与订单编号');
            }
            $upWhere=[['order_id', 'eq', $orderid],['process_name', 'eq', $process_name],['user_number', 'eq', $memberNumber],['is_disabled','eq',0]];
            if(!empty($dataid)) {
                $upWhere[]=['id', 'eq', $dataid];
            }
            $editInfo=db('user_process up')                ->where($upWhere)
                ->group('up.order_id,up.process_name,up.user_number')->order("id")->find();
            if($broke_count!=9999){ //设置报损数
                $insertData = [
                    'factory_name'=>'',
                    'user_name'=>'',
                    'user_number'=>'',
                    'bar_num'=>0,
                    'process_quintity'=>0,
                    'quintity' => $broke_count,
                    'check_remark' => '',
                    'update_date' => date('Y-m-d H:i:s'),
                    'last_editer'=>ADMIN_ID,
                    'creater'=>ADMIN_ID,
                    'create_time' => time(),
                ];
                $list = db('user_process up')->field("*")
                    ->where([['order_id', 'eq',$orderid],['check_state','elt',1]])
                    ->group('up.order_id,up.process_name,up.user_number')->order("id asc")->select();
                foreach ($list as $key=>$item){
                    /*$insertData['factory_name']=$item['factory_name'];
                    $insertData['user_name']=$item['user_name'];
                    $insertData['is_broke_data']=1;
                    $insertData['user_number']=$item['user_number'];
                    $newInsertData=array_merge($item,$insertData);
                    $haveBrokeData=db('user_process up')->where([['order_id', 'eq', $orderid],['process_name', 'eq', $item['process_name']],['user_number', 'eq', $item['user_number']]
                        ,['is_disabled','eq',0],['is_broke_data','eq',1]])->find();
                    if(!empty($haveBrokeData)){
                        db('user_process')->where([['id', '=', $haveBrokeData['id']]])->update(['quintity'=>$broke_count]);
                    }else{ //新增报损数
                        unset($newInsertData['id']);
                        $processid = db('user_process')->insertGetId($newInsertData);
                    }*/
                    $brokeInsertData=[
                        'order_id'=>$editInfo['order_id'],'client_ordernum'=>$editInfo['client_ordernum'],'broke_make_count'=>$broke_count,
                        'last_editer'=>ADMIN_ID,
                        'update_time'=>time(),
                        'create_time' => time(),
                    ];
                    $haveBrokeData=db('user_process_ext upext')->where([['order_id', '=', $editInfo['order_id']]])->find();
                    if(!empty($haveBrokeData)){
                        unset($brokeInsertData['create_time']);
                        db('user_process_ext')->where([['id', '=', $haveBrokeData['id']]])->update($brokeInsertData);
                    }else{
                        db('user_process_ext')->insertGetId($brokeInsertData);
                    }
                    //echo lastsql();
                }
            }elseif($process_remark!=''){
                /*$editInfo=db('user_process up')                ->where($upWhere)
                    ->group('up.order_id,up.process_name,up.user_number')->order("id")->find();
                db('user_process')->where([['id', '=', $editInfo['id']]])->update(['last_editer'=>ADMIN_ID,'check_remark'=>$process_remark]); //$editInfo['check_remark']." "*/
                $list = db('user_process up')->field("*")
                    ->where([['order_id', 'eq',$orderid],['check_state','elt',1]])
                    ->group('up.order_id,up.process_name,up.user_number')->order("id asc")->select();
                foreach ($list as $key=>$item) {
                    db('user_process')->where([['id', '=', $item['id']]])->update(['last_editer'=>ADMIN_ID,'check_remark'=>$process_remark]);
                }
            }
            return $this->Json(1, '处理成功');
        }
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        if($action=='setSalaryMonth'){ //设置帐单工资月份
            $worktimemonth=$this->request->param('billmonth','');//2022-07
            $list=db('user_process')->where([['id', 'in', $ids]])->select();
            $work_time=strtotime(date($worktimemonth."-02 H:i:s"));
            foreach ($list as $k=>$v){
                $temp=db('user_process')->where([['order_id', '=', $v['order_id']],['process_name', '=', $v['process_name']],['user_number', '=', $v['user_number']]])->update([
                    'work_time' => $work_time,
                ]);
            }
            return $this->Json(1, '设置结算月份成功', $temp);
        }
        //--- 开始审核账单到对账中
        $orderids=[];
        $list=db('user_process')->where([['id', 'in', $ids]])->select();
        foreach ($list as $k=>$v){
            $orderids[]=$v['order_id'];
            if ($v['process_price'] <= 0) {
                return $this->Json(102, '有单价为0的账单，不能审核');
            }
        }
        $instockRet=db("sku_stock_log log")
            ->field("sum(available_count) as available_count,log.factory_id,log.client_ordernum")//+defective_count
            ->where('action_type','eq',1)->group("log.client_ordernum")->buildSql();
        //出库其它单库存数统计
        $checkOutStockRet=db("sku_stock_log log")
            ->field("sum(available_count) as available_checkout_count,log.out_ordernum,log.client_ordernum")
            ->where('action_type','eq',2)->group("log.out_ordernum")->buildSql();

        $processCountRet=db('user_process up')->field("store_count as store_count2,up.order_id,process_name,sum(up.quintity) as tot_quintity2,up.id as id,sum(process_quintity) as process_quintity2,
        (CASE  WHEN up23.available_count IS NULL THEN 0 ELSE up23.available_count END) as available_count,
        (CASE  WHEN upexp.broke_make_count IS NULL THEN 0 ELSE upexp.broke_make_count END) as broke_make_count,
        (CASE  WHEN outstock.available_checkout_count IS NULL THEN 0 ELSE outstock.available_checkout_count END) as available_checkout_count")
            ->join('order o', 'up.order_id = o.id','left')
            ->join('user_process_ext upexp', 'up.order_id = upexp.order_id','left')
            ->join([$instockRet=> 'up23'], 'o.client_ordernum = up23.client_ordernum','left')
            ->join([$checkOutStockRet=> 'outstock'], 'o.client_ordernum = outstock.out_ordernum','left')
            ->group('order_id,process_name')->buildSql();
        $sqlwhere='';$joinType='inner';
        $sqlwhere .=" and ABS((up2.available_count+up2.store_count2+up2.broke_make_count-available_checkout_count) - tot_quintity2) > 5";
        $orderPorcessCountRet = db('user_process up')
            ->join('order o', 'up.order_id = o.id','left')
            ->join([$processCountRet=> 'up2'], 'up.order_id = up2.order_id and up.process_name=up2.process_name'.$sqlwhere,$joinType)
            ->where([['up.order_id', 'in', $orderids]])->field("up.order_id as order_id,up.process_name as process_name,o.client_ordernum,
            ABS((up2.available_count+up2.store_count2+up2.broke_make_count-available_checkout_count) - tot_quintity2) as diff_count,
                    sum(up.quintity) as tot_quintity,group_concat(up.check_remark SEPARATOR '') as check_remark,
                    sum(up.process_quintity) as process_quintity,up.id as id")
            ->group('up.order_id,up.process_name')->select();
        $errOrderPorcessCount=[];
        foreach ($orderPorcessCountRet as $key=>$val){
            $errOrderPorcessCount[$val['order_id'].$val['process_name']]=$val;
        }

        foreach ($list as $k=>$val){
            if(!empty($errOrderPorcessCount[$val['order_id'].$val['process_name']]) && empty($errOrderPorcessCount[$val['order_id'].$val['process_name']]['check_remark'])){
                $errmsg=$errOrderPorcessCount[$val['order_id'].$val['process_name']]['client_ordernum']." ".$val['process_name']." 结算与入仓差异件数".$errOrderPorcessCount[$val['order_id'].$val['process_name']]['diff_count'];
                return $this->Json(102, $errmsg.'，差异大于5不能通过，可以增加差异备注，调整结算数量，或补充其它人员的加工数据');die;
            }
        }

        foreach ($list as $k=>$v){
            $updata=[
                'check_state' => $state,
                'f_check_date'=>time(),
                'update_time' => time()
            ];
            if($state==1){
                $updata['check_user']=ADMIN_ID;
            }
            if($state==2){
                unset($updata['f_check_date']);
                $updata['recheck_user']=ADMIN_ID;
            }
            $temp=db('user_process')->where([['order_id', '=', $v['order_id']],['process_name', '=', $v['process_name']],['user_number', '=', $v['user_number']]])->update($updata);
        }
        return $this->Json(1, '审核成功', $temp);

    }

    //编辑车间/尾部工序工价 与加工数量
    public function doEditStatementsProcessPrice(){
        $orderId = $this->request->param('order_id');
        $numberArr = $this->request->param('number/a', []);
        $process_name_arr=$this->request->param('process_name/a', []);
        $old_process_price_arr=$this->request->param('old_process_price/a', []);
        $process_price_arr=$this->request->param('process_price/a', []);
        $action=$this->request->param('action', '');
        $factoryKV = getFactoryKV();
        if($action=='changeQuintity'){  //修改加工数量
            $postEditData=$this->request->param();
            $where[]=['user_number','=',$postEditData['old_user_number']];
            $where[]=['order_id','=',$postEditData['old_order_id']];
            $where[]=['process_name','=',$postEditData['old_process_name']];
            $oldprocess=db('user_process')->where($where)->find();
            $batchUpdata=$postEditData;
            unset($batchUpdata['changelist']);unset($batchUpdata['old_user_number']);unset($batchUpdata['old_order_id']);unset($batchUpdata['old_process_name']);
            unset($batchUpdata['action']);
            if(empty($batchUpdata['user_number'])) unset($batchUpdata['user_number']);
            if(empty($batchUpdata['process_name'])) unset($batchUpdata['process_name']);
            if(empty($batchUpdata['factory_name'])) unset($batchUpdata['factory_name']);
            if(empty($batchUpdata['process_stage'])) unset($batchUpdata['process_stage']);
            $diffWorktimeCount=db("user_process")->where($where)->group("FROM_UNIXTIME(work_time,'%Y-%m-%d')")->select();//是否存在不同完成时间的工序
            if($batchUpdata['work_time'] == date("Y-m-d",$oldprocess['work_time']) && count($diffWorktimeCount)<=1) unset($batchUpdata['work_time']);
            if(empty($batchUpdata['work_time'])) unset($batchUpdata['work_time']);
            if(!empty($batchUpdata['factory_name']) && !in_array($batchUpdata['factory_name'],$factoryKV)) {
                return $this->Json(0, "操作失败，工厂名称不存在 ".$batchUpdata['factory_name']);
            }
            if(count($batchUpdata)>0){
                if(!empty($batchUpdata['work_time'])) $batchUpdata['work_time']=strtotime($batchUpdata['work_time']." ".date("H:i:s",$oldprocess['work_time']));
                $batchUpdata['last_editer']=ADMIN_ID;
                $res = db('user_process')->where($where)->update($batchUpdata);
            }
            $changelist=json_decode(htmlspecialchars_decode($this->request->param('changelist')),true);
            if(!is_array($changelist) || count($changelist)<1){
                return $this->Json(1);
                //return $this->Json(0, "操作失败，传入修改的参数有误",['source_changelist'=>$this->request->param('changelist'),'decode_changelist'=>$changelist]);
            }
            $changeids=array_column($changelist,'id');
            $oldRet=db('user_process')->where([['id', 'in',$changeids]])->select();
            $oldIdList=arrayByKey($oldRet,'id');
            $changeState=0;
            try {
                db()->startTrans();
                foreach ($changelist as $key => $changeInfo) {
                    $oldinfo = $oldIdList[$changeInfo['id']];
                    if ($changeInfo['tot_quintity'] != $oldinfo['quintity'] || $changeInfo['tot_quintity']==0 || $changeInfo['check_remark'] != $oldinfo['check_remark']) {
                        if ($changeInfo['tot_quintity'] != $oldinfo['old_quintity'] || $changeInfo['tot_quintity']==0) {
                            $updata['old_quintity'] = $changeInfo['check_state']==2 ? $oldinfo['quintity'] : $oldinfo['old_quintity'];
                            $updata['quintity'] = $changeInfo['tot_quintity'];
                        }
                        $updata['check_remark'] = $changeInfo['check_remark'];
                        $updata['last_editer']=ADMIN_ID;
                        $res = db('user_process')->where([['id', '=', $changeInfo['id']]])->update($updata);
                        $changeState = 1;
                    }
                    $checkState = $changeInfo['check_state'] == 2 ? 1 : 0;
                    if ($changeState) { //提交重审的业务逻辑，暂不启用
                        /*$res = db('user_process')->where([['order_id', '=', $changeInfo['order_id']],
                            ['user_number', '=', $changeInfo['user_number']],['process_name', '=', $changeInfo['process_name']]])->update(['check_state' => $checkState,'recheck_user'=>0]);*/
                    }
                }
                db()->commit();
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
            return $this->Json(1);
        }else{
            try {
                db()->startTrans();
                $log_str='';
                foreach ($process_name_arr as $k => $v) {
                    $data = array();
                    $data['process_price'] = $process_price_arr[$k];
                    $data['update_time'] = time();
                    if($process_price_arr[$k]!=$old_process_price_arr[$k]){ //有调整则修改
                        $log_str.="将".$process_name_arr[$k]."的单价从 ".$old_process_price_arr[$k].'调整为'.$process_price_arr[$k].',';
                        $res = db('user_process')->where([['order_id', '=', $orderId],['process_name', '=', $process_name_arr[$k]]])->update($data);
                    }
                }
                $this->addOrderLog($orderId, '', '工价调整 '.$log_str);
                db()->commit();
                return $this->Json(1);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }
    }


    //车间/尾部工价账单结算
    public function statementsSettle(){
        $status = $this->request->param('status/d', 1);
        $process_stage=$this->request->param('process_stage/d', 2); //2车间与尾部对账区别参数,3尾部
        $factoryKV = getFactoryKV(false);
        if ($this->request->isAjax()|| $this->request->param('export')) {
            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $export     = $this->request->param('export/d', 0);
            $factoryId   = $this->request->param('factory_id/s', '');
            $client_ordernum   = $this->request->param('client_ordernum', '');
            $sku = $this->request->param('sku', '');
            $overDateRange=$this->request->param('create_date_range');
            list($startTime, $endTime) = $overDateRange != '' ? array_map('strtotime', explode('~', $overDateRange)) : [strtotime(date("Y-m-01 00:00:00",strtotime("-6 month"))),time()];
            $factoryIdarr=array_keys($factoryKV);
            $where[]=['process_stage', 'eq', $process_stage];
            if($status==1){ //待审
                $where[]=['check_state', 'eq', 1];
            }else{
                $where[]=['check_state', 'gt', 1];
            }
            if ($export) {
                set_time_limit(0);
                $page = 1;$limit = 99999;
            }
            if($sku) $where[] = ['o.sku', '=', $sku];
            if($client_ordernum) $where[] = ['o.client_ordernum', '=', $client_ordernum];
            if($overDateRange) $where[] = ['up.work_time', 'between', [$startTime, $endTime+86399]];
            if($factoryId) $where[] = ['up.factory_name', '=', $factoryId];

            $total = db('user_process up')->where($where)->join('order o', 'up.order_id = o.id','left')
                ->group('order_id,process_name,user_number')->count();
            $list = db('user_process up')
                ->join('order o', 'up.order_id = o.id','left')
                ->join('sku sk', 'o.sku = sk.sku','left')
                ->where($where)->page($page)->field("*,sum(up.quintity) as tot_quintity,up.id as id")
                ->group('order_id,process_name,user_number')->limit($limit)->order('up.id desc')->select();
            if($total>0){
                foreach ($list as $k=>&$vinfo){
                    $vinfo['process_name_json']=json_encode(db('user_process up')->where([['order_id', 'eq', $vinfo['order_id']],['process_stage', 'eq', $process_stage]])->field("distinct process_name,process_price")->select());

                    $vinfo['money_total']=sprintf('%.2f',$vinfo['tot_quintity']*$vinfo['process_price']);
                    $list[$k]['work_time'] =  date('Y-m-d H:i', $list[$k]['work_time']);//出货时间
                    $vinfo['pic_res'] = trim($vinfo['ori_pic']) == '' ? $vinfo['pic'] : $vinfo['ori_pic'];
                }
            }
            $needcheckCount=db('user_process up')->where([['check_state', 'eq', 1],['process_stage', 'eq', $process_stage]])->group('order_id,process_name,user_number')->count();
            $checkedCount=db('user_process up')->where([['check_state', 'gt', 1],['process_stage', 'eq', $process_stage]])->group('order_id,process_name,user_number')->count("id");;

            $data = [];
            $data['data'] = $list;
            if ($export) {//导出
                $this->exportSkuStockXls('成衣库存列表-' .date('YmdHis'), $data['data']);
                exit;
            }
            $data['needcheckCount'] = $needcheckCount;
            $data['checkedCount'] = $checkedCount;
            $data['status']=$status;
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $allFactorys=db('user_process up')->where([['process_stage', 'eq', $process_stage]])->field("distinct factory_name")->select();
        $factoryKV=[];
        foreach($allFactorys as $key=>$info){
            $factoryKV[$info['factory_name']]=$info['factory_name'];
        }
        $assign = [
            'process_stage'=>$process_stage,
            'status'=>$status,
            'factoryKV' => ['' => '请选择'] + $factoryKV
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     *对账中驳回对账账单
     * @author: sparkguo
     * @Date: 2022/11/24 14:04
     */
    public function callbackBills(){
        $state = $this->request->param('status/d', 0);
        $ids = $this->request->param('id', []);
        $state=0; //0为驳回，1为生成帐单，该方法只能限制成驳回
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        $list=db('user_process')->where([['id', 'in', $ids]])->select();
        foreach ($list as $k=>$v){
            $temp=db('user_process')->where([['order_id', '=', $v['order_id']],['process_name', '=', $v['process_name']],['user_number', '=', $v['user_number']]])->update([
                'check_state' => $state,
                'recheck_user'=>ADMIN_ID,
                'update_time' => time()
            ]);
        }
        return $this->Json(1, '审核成功', $temp);
    }

    public function setStatementsSettle(){
        $state = $this->request->param('status/d', 1);
        $ids = $this->request->param('id', []);
        $pay_state=$this->request->param('pay_state','');
        $action=$this->request->param('action','');
        $list=db('user_process')->where([['id', 'in', $ids]])->select();
        if($pay_state > 0){//设置复核状态 3为待复核
            $pay_state=$pay_state==3 ? 0 :$pay_state;
            $pay_code= $pay_state==0 ? '' :date('ymdHis'); //设置为空后对账中的账可以合并到待复核列表里
            foreach ($list as $k=>$v) {
                list($startTime, $endTime) =  [strtotime(date("Y-m-01 00:00:00",$v['work_time'])),strtotime(date("Y-m-t 23:59:59",$v['work_time']))];//获取一月整时间段 用于更新
                $temp = db('user_process')->where([['work_time', 'between', [$startTime,$endTime]], ['check_state', '=', 2], ['user_number', '=', $v['user_number']]])->update([
                    'pay_state' => $pay_state,'pay_code'=>$pay_code, 'update_time' => time()
                ]);
            }
            return $this->Json(1, '设置成功', $temp);
        }

        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        $list=db('user_process')->where([['id', 'in', $ids]])->select();
        foreach ($list as $k=>$v){
            $temp=db('user_process')->where([['order_id', '=', $v['order_id']],['process_name', '=', $v['process_name']],['user_number', '=', $v['user_number']]])->update([
                'check_state' => $state,
                'recheck_user'=>ADMIN_ID,
                'update_time' => time()
            ]);
        }
        return $this->Json(1, '审核成功', $temp);
    }

    private function _get_statData($type = 0)
    {
        switch ($type) {
            case 0:
                $statData = [
                    1 => db('order_progress_price opp')
                        ->where([
                            ['opp.status', 'in', [0, 1101, 1102]]
                        ])
                        ->count(),
                    2 => db('order_progress_price opp')
                        ->where([
                            ['opp.status', '=', 1120]
                        ])
                        ->count(),
                ];
                return $statData;
                break;
            case 1:
                $statData = [
                    1 => db('order_progress_price opp')
                        ->where([
                            ['opp.status', '=', 1120]
                        ])
                        ->count(),
                    2 => db('order_progress_price opp')
                        ->where([
                            ['opp.status', '=', 1200]
                        ])
                        ->count(),
                ];
                return $statData;
                break;
        }

    }


    /**
     * 修改字段
     * @date 2022/01/20
     * @author zhuguosen 905502314@qq.com
     */
    public function editUnit()
    {
        $param = [
            'id' => $this->request->param('id/d', 0),
            'field' => $this->request->param('field/s', 0),
            'value' => $this->request->param('value/s', 0),
        ];
        $havedata=db('order_progress_price_change')->where([
            ['order_id', '=', $param['id']],
            ['process_keywords', '=', 'caijian'],
        ])->find();
        if($havedata){
            $temp = db('order_progress_price_change')->where([
                ['id', '=', $havedata['id']]
            ])->update([
                $param['field'] => $param['value'],
            ]);
        }else{
            $temp=db('order_progress_price_change')->insert([
                'process_name'=>'裁剪',
                'author_id'=>ADMIN_ID,
                'process_price'=> $param['value'],
                'order_id' => $param['id'],
                'process_keywords' =>'caijian',
                'update_time' => time(),
                'create_time' => time()
            ]);
        }
        if ($temp == 1) {
            return $this->Json(1, '修改成功', $temp);
        }
        return $this->Json(10, '修改失败', $temp);
    }

    /**
     * 修改结算数量
     */
    public function editPayCount()
    {
        $param = [
            'id' => $this->request->param('id/d', 0),
            'field' => $this->request->param('field/s', 0),
            'value' => $this->request->param('value/s', 0),
        ];
        $temp = db('order_progress_price')->where([
            ['id', '=', $param['id']]])->update([
            $param['field'] => $param['value']]);

        if ($temp == 1) {
            return $this->Json(1, '修改成功', $temp);
        }
        return $this->Json(10, '修改失败', $temp);
    }

    /**
     * 审核 ，驳回 等动作
     * @date 2021/12/25
     * @author zhuguosen 905502314@qq.com
     */
    public function check()
    {
        //1,参数处理
        $status = $this->request->param('status/d', 0);
        $process_stage = $this->request->param('process_stage/d', 0);
        $ids = $this->request->param('id', []);
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        //2,表修改
        switch ($status) {
            case 1120:
                switch ($process_stage) {
                    case 1://1,载床对帐  裁剪数为0不能审核
                        $list = db('order_progress_price opp')
                            ->field('opp.id,opp.order_id,opp.action_str
                ,sum(osize.shicai_count) sum_shicai_count 
                ')
                            ->join('order_size osize ', 'osize.order_id=opp.order_id', 'left')
                            ->where([
                                ['opp.id', 'in', $ids],
                            ])
                            ->group('opp.order_id')
                            ->select();
                        foreach ($list as $k => $v) {
                            if (intval($v['sum_shicai_count']) <= 0) {
                                return $this->Json(102, '实裁总数为0，不能审核');
                            }
                        }
                        break;
                    default:
                        return $this->Json(101, '失败');
                        break;
                }
                Db::startTrans();
                try {
                    foreach ($list as $k => $v) {
                        $list[$k]['action_str'] = unserialize($list[$k]['action_str']);
                        $list[$k]['action_str'] == false && $list[$k]['action_str'] = [];
                        $list[$k]['action_str'][] = [ADMIN_ID, time(), 'check_1120'];
                        $temp = db('order_progress_price')->where([
                            ['id', '=', $v['id']],
                            ['status', 'in', [0, 1101, 1102]],
                        ])->update([
                            'status' => 1120,
                            'update_time' => time(),
                            'action_str' => serialize($list[$k]['action_str']),
                        ]);
                        if ($temp != 1) {
                            Db::rollback();
                            return $this->Json(110, '失败', $temp);
                        }
                    }
                    Db::commit();
                    return $this->Json(1, '审核成功', $temp);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->Json(100, '失败');
                }
                break;
            case 1102://驳回
                switch ($process_stage) {
                    case 1://1,载床对帐
                        $list = db('order_progress_price opp')
                            ->field('opp.id,opp.order_id,opp.action_str
                ,sum(osize.shicai_count) sum_shicai_count 
                ')
                            ->join('order_size osize ', 'osize.order_id=opp.order_id', 'left')
                            ->where([
                                ['opp.id', 'in', $ids],
                            ])
                            ->group('opp.order_id')
                            ->select();
                        break;
                    default:
                        return $this->Json(101, '失败');
                        break;
                }
                $temp=db('order_progress_price')->where([
                    ['id', 'in', $ids],
                ])->delete();
                return $this->Json(1, '驳回成功', $temp);
                break;
            case 11200://返审--已完成付款后的的返审
                switch ($process_stage) {
                    case 1://1,载床对帐  裁剪数为0不能审核
                        $list = db('order_progress_price opp')
                            ->field('opp.id,opp.order_id,opp.action_str
                ,opp.pay_time
                ')
                            ->where([
                                ['opp.id', 'in', $ids],
                            ])
                            ->group('opp.order_id')
                            ->select();
                        foreach ($list as $k => $v) {
                            if (strtotime($v['pay_time']) + 7 * 24 * 3600 <= time()) {//7 * 24 * 3600
                                return $this->Json(102, '7天后的单，不能返审');
                            }
                        }
                        break;
                    default:
                        return $this->Json(101, '失败');
                        break;
                }
                Db::startTrans();
                try {
                    foreach ($list as $k => $v) {
                        $list[$k]['action_str'] = unserialize($list[$k]['action_str']);
                        $list[$k]['action_str'] == false && $list[$k]['action_str'] = [];
                        $list[$k]['action_str'][] = [ADMIN_ID, time(), 'check_11200'];
                        $temp = db('order_progress_price')->where([
                            ['id', '=', $v['id']],
                            ['status', '=', 1200],
                        ])->update([
                            'status' => 1120,
                            'update_time' => time(),
                            'action_str' => serialize($list[$k]['action_str']),
                        ]);
                        if ($temp != 1) {
                            Db::rollback();
                            return $this->Json(110, '失败', $temp);
                        }
                    }
                    Db::commit();
                    return $this->Json(1, '审核成功', $temp);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->Json(100, '失败');
                }
                break;
        }
        return $this->Json(10, '失败');
    }

    public function cuttingMoney()
    {
        $status = $this->request->param('status/d', 1);
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $where = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            switch ($status) {
                case 1:
                    $where = $this->_where_cuttingMoney($where);
                    $order = "opp.id asc";
                    $list = db('order_progress_price opp')
                        ->field('opp.id,opp.order_id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.caichuang_over_time,o.caichuang_chuanghao,o.caichuang_position,o.caichuang_user_id,o.caichuang_type
                ,s.pic,s.ori_pic,pay_count
                ,ft.type as ft_type,ft.name as ft_name
                ,sum(osize.shicai_count) sum_shicai_count ,sum(osize.delivery_count) sum_delivery_count ,sum(osize.store_count) sum_store_count 
                ,opp.process_name,opp.process_price
                ,su.username as caichuang_user_name
                ')
                        ->join('order o', "o.id=opp.order_id", 'left')
                        ->join('system_user su ', 'su.id=o.caichuang_user_id', 'left')
                        ->join('factory ft', "ft.id=o.factory_id", 'left')
                        ->join('sku s', "o.sku=s.sku", 'left')
                        ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                        ->where($where)->page($page)->limit($limit)->orderRaw($order)
                        ->group('opp.order_id')
                        ->select();
                    $count = db('order_progress_price opp')
                        ->join('order o', "o.id=opp.order_id", 'left')
                        ->join('system_user su ', 'su.id=o.caichuang_user_id', 'left')
                        ->join('factory ft', "ft.id=o.factory_id", 'left')
                        ->join('sku s', "o.sku=s.sku", 'left')
                        ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                        ->where($where)
                        ->group('opp.order_id')
                        ->count();
                    foreach ($list as $k => $v) {
                        $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                        $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                        $list[$k]['caichuang_over_time'] = intval($list[$k]['caichuang_over_time']) <= 0 ? '' : date('Y-m-d H:i', $list[$k]['caichuang_over_time']);//裁剪时间
                        $list[$k]['caichuang_position_txt'] = arrayGet(config('mimo.caichuang_position'), $v['caichuang_position'], '');
                        $list[$k]['sum_available_count'] = 0;
                        //入米莫库存的数据查询
                        $temp = db('sku_stock stk')->field('stk.available_detail')->where([['stk.client_ordernum', '=', $v['client_ordernum']], ['stk.sku', '=', $v['sku']]])->select();
                        foreach ($temp as $k2 => $v2) {
                            $a = json_decode($v2['available_detail']);
                            if(!is_array($a)){
                                $list[$k]['sum_available_count']=0;
                                continue;
                            }
                            foreach ($a as $k3 => $v3) {
                                $list[$k]['sum_available_count'] += $v3;
                            }
                        }

                        $list[$k]['sum_pay_money'] = sprintf("%.2f", $v['pay_count'] * $v['process_price']);
                    }
                    break;
                case 2:
                    $where = $this->_where_cuttingMoney($where);
                    $order = "opp.id asc";
                    $list = db('order_progress_price opp')
                        ->field("
                        DATE_FORMAT(opp.pay_time,'%Y-%m') as pay_month
                        ,max(opp.pay_time) as max_pay_time
                        ,opp.factory_id,ft.name as ft_name_all
                         ,sum(opp.sum_shicai_count) sum_shicai_count_all
                           ,sum(opp.sum_pay_money) sum_pay_money_all
                ")
                        ->join('factory ft', "ft.id=opp.factory_id", 'left')
                        ->where($where)->page($page)->limit($limit)->orderRaw($order)
                        ->group("opp.factory_id, pay_month")
                        ->select();
                    foreach ($list as $k => $v) {
                        $list[$k]['id'] = "{$v['factory_id']},{$v['pay_month']}";
                    }
                    $count = db('order_progress_price opp')
                        ->join('factory ft', "ft.id=opp.factory_id", 'left')
                        ->where($where)
                        ->group("opp.factory_id, DATE_FORMAT(opp.pay_time,'%Y-%m')")
                        ->count();
                    break;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status' => $status,
                'statData' => $this->_get_statData(1),
            ];
            return json($result);
        }
        $assign = [
            'status' => 1,
            'statData' => $this->_get_statData(1),
            'factoryKV' => [0 => '请选择'] + getFactoryKV(false),
            'caichuang_position' => [-1 => '请选择'] + config('mimo.caichuang_position'),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_cuttingMoney($where)
    {
        $where[] = ['opp.process_stage', '=', 1];
        $status = $this->request->param('status/d', 1);
        switch ($status) {
            case 1:
                $where[] = ['opp.status', '=', 1120];
                $clientOrdernum = $this->request->param('client_ordernum/s', '');
                $sku = $this->request->param('sku/s', '');
                $factory_id = $this->request->param('factory_id/d', 0);
                $caichuang_position = $this->request->param('caichuang_position/d', -1);
                $createDateRange = $this->request->param('create_date_range/s', '');
                if ($clientOrdernum != '') {
                    $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
                }
                if ($sku != '') {
                    $where[] = ['o.sku', 'like', "%" . $sku . "%"];
                }
                if ($factory_id > 0) {
                    $where[] = ['o.factory_id', '=', $factory_id];
                }
                if ($caichuang_position > -1) {
                    $where[] = ['o.caichuang_position', '=', $caichuang_position];
                }
                if ($createDateRange != '') {
                    list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                    $where[] = ['o.caichuang_over_time', 'between', [$startTime, $endTime + 86399]];
                }
                break;
            case 2:
                $where[] = ['opp.status', '=', 1200];
                $factory_id = $this->request->param('factory_id/d', 0);
                if ($factory_id > 0) {
                    $where[] = ['opp.factory_id', '=', $factory_id];
                }
                break;
        }
        return $where;
    }

    public function accountPayment()
    {
        //1,参数处理
        $process_stage = $this->request->param('process_stage/d', 0);
        $ids = $this->request->param('id', []);
        foreach ($ids as $k => $id) {
            $ids[$k] = intval($id);
        }
        //2,表修改
        switch ($process_stage) {
            case 1://1,载床对帐  裁剪数为0不能审核
                $list = db('order_progress_price opp')
                    ->field('opp.id,opp.order_id,opp.action_str,opp.process_price
                   , o.factory_id , o.group_id,o.client_ordernum,o.sku
                ,sum(osize.shicai_count) sum_shicai_count ,sum(osize.delivery_count) sum_delivery_count ,sum(osize.store_count) sum_store_count 
                ')
                    ->join('order o', "o.id=opp.order_id", 'left')
                    ->join('order_size osize ', 'osize.order_id=opp.order_id', 'left')
                    ->where([
                        ['opp.id', 'in', $ids],
                    ])
                    ->group('opp.order_id')
                    ->select();
                foreach ($list as $k => $v) {
                    $list[$k]['sum_available_count'] = 0;
                    //入米莫库存的数据查询
                    $temp = db('sku_stock stk')->field('stk.available_detail')->where([['stk.client_ordernum', '=', $v['client_ordernum']], ['stk.sku', '=', $v['sku']]])->select();
                    foreach ($temp as $k2 => $v2) {
                        $a = json_decode($v2['available_detail']);
                        foreach ($a as $k3 => $v3) {
                            $list[$k]['sum_available_count'] += $v3;
                        }
                    }
                    $temp_num = 0;
                    $temp_num == 0 && $v['sum_store_count'] > 0 && $temp_num = $v['sum_store_count'];
                    $temp_num == 0 && $v['sum_delivery_count'] > 0 && $temp_num = $v['sum_delivery_count'];
                    $temp_num == 0 && $v['sum_shicai_count'] > 0 && $temp_num = $v['sum_shicai_count'];
                    $list[$k]['sum_pay_money'] = sprintf("%.2f", ($temp_num + $list[$k]['sum_available_count']) * $v['process_price']);
                }
                break;
            default:
                return $this->Json(101, '失败');
                break;
        }
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                $list[$k]['action_str'] = unserialize($list[$k]['action_str']);
                $list[$k]['action_str'] == false && $list[$k]['action_str'] = [];
                $list[$k]['action_str'][] = [ADMIN_ID, time(), 'check_1200'];
                $temp = db('order_progress_price')->where([
                    ['id', '=', $v['id']],
                    ['status', '=', 1120],
                ])->update([
                    'status' => 1200,
                    'sum_shicai_count' => $v['sum_shicai_count'],
                    'sum_delivery_count' => $v['sum_delivery_count'],
                    'sum_store_count' => $v['sum_store_count'],
                    'sum_available_count' => $v['sum_available_count'],
                    'sum_pay_money' => $v['sum_pay_money'],
                    'factory_id' => $v['factory_id'],
                    'group_id' => $v['group_id'],
                    'pay_time' => date('Y-m-d H:i:s'),
                    'update_time' => time(),
                    'action_str' => serialize($list[$k]['action_str']),
                ]);
                if ($temp != 1) {
                    Db::rollback();
                    return $this->Json(110, '失败', $temp);
                }
            }
            Db::commit();
            return $this->Json(1, '审核成功', $temp);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->Json(100, '失败');
        }
    }

    public function billList()
    {
        $id = $this->request->param('id/s', '');
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $where = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $export = $this->request->param('export/d', 0);
            if ($export) {
                set_time_limit(0);
                ini_set('memory_limit', '1024M');
                $page = 1;
                $limit = 99999;
            }
            $where[] = ['opp.process_stage', '=', 1];
            $where[] = ['opp.status', '=', 1200];
            $temp_f_date = explode(',', $id);
            $where[] = ['opp.factory_id', '=', $temp_f_date[0]];

            $order = "opp.id asc";
            $list = db('order_progress_price opp')
                ->field('opp.id,opp.order_id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.caichuang_over_time,o.caichuang_chuanghao,o.caichuang_position,o.caichuang_user_id,o.caichuang_type
                ,s.pic,s.ori_pic,opp.pay_count
                ,ft.type as ft_type,ft.name as ft_name
                ,sum(osize.shicai_count) sum_shicai_count ,sum(osize.delivery_count) sum_delivery_count ,sum(osize.store_count) sum_store_count 
                ,opp.process_name,opp.process_price
                ,su.username as caichuang_user_name
                ')
                ->join('order o', "o.id=opp.order_id", 'left')
                ->join('system_user su ', 'su.id=o.caichuang_user_id', 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->where($where)
                ->whereRaw("DATE_FORMAT(opp.pay_time,'%Y-%m')='{$temp_f_date[1]}'")
                ->page($page)->limit($limit)->orderRaw($order)
                ->group('opp.order_id')
                ->select();
            $count = db('order_progress_price opp')
                ->join('order o', "o.id=opp.order_id", 'left')
                ->join('system_user su ', 'su.id=o.caichuang_user_id', 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->where($where)
                ->group('opp.order_id')
                ->count();
            foreach ($list as $k => $v) {
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                $list[$k]['caichuang_over_time'] = intval($list[$k]['caichuang_over_time']) <= 0 ? '' : date('Y-m-d H:i:s', $list[$k]['caichuang_over_time']);//出货时间
                $list[$k]['caichuang_position_txt'] = arrayGet(config('mimo.caichuang_position'), $v['caichuang_position'], '');
                $list[$k]['sum_available_count'] = 0;
                //入米莫库存的数据查询
                $temp = db('sku_stock stk')->field('stk.available_detail')->where([['stk.client_ordernum', '=', $v['client_ordernum']], ['stk.sku', '=', $v['sku']]])->select();
                foreach ($temp as $k2 => $v2) {
                    $a = json_decode($v2['available_detail']);
                    foreach ($a as $k3 => $v3) {
                        $list[$k]['sum_available_count'] += $v3;
                    }
                }
                $list[$k]['sum_pay_money'] = sprintf("%.2f", $v['pay_count'] * $v['process_price']);
            }
            if ($export) {
                $this->_exportXls("栽床对帐-{$list[0]['ft_name']}-{$temp_f_date[1]}月-" . date('YmdHis'), $list);
                exit;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'ext' => [
                    'temp_f_date' => $temp_f_date,
                    'ft_name' => $list[0]['ft_name'],
                ],
            ];
            return json($result);
        }
        $assign = [
            'id' => $id,
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 导出
     *
     */
    private function _exportEmployeeSalaryXls($title, &$list)
    {
        ini_set('memory_limit', '1200M');
        $params = [];
        $data = [];
        foreach ($list as $k => $v) {//'完成时间',入仓时间, '姓名', '组别', 'SKU', '订单号', '工序', '规格', '数量', '单价', '金额', '备注', '其它', '工厂', 'MES入仓数', '米莫入库数',
            $data[] = [
                $v['work_time'],//
                $v['store_time'],
                $v['user_name'],
                $v['group_name'],
                $v['sku'],
                $v['client_ordernum'],
                $v['process_name'],
                $v['process_quintity'],
                $v['tot_quintity'],
                $v['process_price'],
                $v['money_total'],
                $v['check_remark'] ,
                $v['factory_name'],
                $v['store_count'],
                $v['stock_count'],
                $v['broke_make_count'],
                $v['broke_cost_count'],
                $v['count_diff'],
            ];
            unset($list[$k]);
        }
        $params['file'] = $title;
        $params['sheet'] = [
            [
                //薪资月份	姓名	组别	SKU	订单号	工序	规格	数量	单价	金额	备注	库存	工厂
                'head' => ['完成时间','入仓时间', '姓名', '组别', 'SKU', '订单号', '工序', '加工数量','结算数量', '单价', '结算金额', '备注', '工厂', 'MES入仓数', '米莫入库数','生产报损','成本报损','差异'], // 表头
                'data' => $data,
            ],
        ];
        unset($list);
        plugins_run('excel/excel/export', $params);
    }
}